code stringlengths 2 1.05M | repo_name stringlengths 5 101 | path stringlengths 4 991 | language stringclasses 3 values | license stringclasses 5 values | size int64 2 1.05M |
|---|---|---|---|---|---|
package MojoPlugins::Validation;
#
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
#
use Mojo::Base 'Mojolicious::Plugin';
use Data::Dumper;
use Data::Dump qw(dump);
use Email::Valid;
sub register {
my ( $self, $app, $conf ) = @_;
$app->renderer->add_helper(
is_username_in_db => sub {
my $self = shift;
my $username = shift;
my $is_in_db;
my @users = $self->db->resultset('TmUser')->search( undef, { columns => [qw/username/] } );
my $fcns ||= MojoPlugins::Validation::Functions->new( $self, @_ );
return $fcns->is_username_in_db_list( @users, $username );
}
);
$app->renderer->add_helper(
is_username_taken => sub {
my $self = shift;
my $username = shift;
my $db_username = $self->db->resultset('TmUser')->find( { username => $username } );
if ( defined($db_username) ) {
$self->field('tm_user.username')->is_like( qr/$db_username/, "Username is already taken" );
}
}
);
$app->renderer->add_helper(
is_email_taken => sub {
my $self = shift;
my $email = $self->param('tm_user.email');
$self->app->log->debug( "email #-> " . Dumper($email) );
my $dbh = $self->db->resultset('TmUser')->search( { email => $email } );
my $count = $dbh->count();
if ( $count > 0 ) {
#$self->app->log->debug( "email #-> " . Dumper($email) );
my $db_email = $dbh->single()->email;
$self->field('tm_user.email')->is_like( qr/ . $db_email . /, "Email is already taken" );
}
}
);
$app->renderer->add_helper(
is_email_format_valid => sub {
my $self = shift;
my $email = $self->param('tm_user.email');
#$self->app->log->debug( "valid email #-> " . Dumper($email) );
if ( defined($email) ) {
unless ( Email::Valid->address( -address => $email, -mxcheck => 1 ) ) {
$self->field('tm_user.email')->is_like( qr/ . $email . /, "Email is not a valid format" );
}
}
}
);
}
package MojoPlugins::Validation::Functions;
use Mojo::Base -strict;
use Scalar::Util;
use Carp ();
use Validate::Tiny;
sub new {
my $class = shift;
my ( $c, $object ) = @_;
my $self = bless {
c => $c,
object => $object
}, $class;
Scalar::Util::weaken $self->{c};
return $self;
}
sub is_username_in_db_list {
my $self = shift;
my $inbound_username = shift;
my @users = shift;
my $is_username_in_db_list;
# This was a very tricky validation because there was no support in the Mojolicious::Plugin::FormFields for
# if a string 'is in' list (the documented 'is_in' should really be called 'is_not_in' because that is
# what it tests.
my @user_names;
foreach my $user_name (@users) {
push( @user_names, $user_name->username );
}
foreach my $user (@users) {
my $username = $user->username;
if ( $username eq $inbound_username ) {
$is_username_in_db_list = 'true';
last;
}
}
return $is_username_in_db_list;
}
1;
| knutsel/traffic_control-1 | traffic_ops/app/lib/MojoPlugins/Validation.pm | Perl | apache-2.0 | 3,361 |
#!/usr/bin/perl
print "Status: 200 OK\r\n";
print "Set-Cookie: name=value; SameSite=Lax\r\n\r\n";
| chromium/chromium | third_party/blink/web_tests/http/tests/inspector-protocol/network/resources/cookie-same-site.pl | Perl | bsd-3-clause | 99 |
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
# This file is machine-generated by mktables from the Unicode
# database, Version 6.1.0. Any changes made here will be lost!
# !!!!!!! INTERNAL PERL USE ONLY !!!!!!!
# This file is for internal use by core Perl only. The format and even the
# name or existence of this file are subject to change without notice. Don't
# use it directly.
return <<'END';
0034
0664
06F4
07C4
096A
09EA
0A6A
0AEA
0B6A
0BEA
0C6A
0CEA
0D6A
0E54
0ED4
0F24
1044
1094
136C
17E4
17F4
1814
194A
19D4
1A84
1A94
1B54
1BB4
1C44
1C54
2074
2084
2163
2173
2463
2477
248B
24F8
2779
2783
278D
3024
3195
3223
3283
4E96
56DB
8086
A624
A6E9
A8D4
A904
A9D4
AA54
ABF4
FF14
1010A
104A4
10A43
10B5B
10B7B
10E63
11055
1106A
110F4
1113A
111D4
116C4
12402
12409
1240F
12418
12421
12426
12430
12438
1243C 1243F
1244C
12452 12453
1D363
1D7D2
1D7DC
1D7E6
1D7F0
1D7FA
1F105
20064
200E2
2626D
END
| liuyangning/WX_web | xampp/perl/lib/unicore/lib/Nv/4.pl | Perl | mit | 1,075 |
# Copyright 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
# https://www.openssl.org/source/license.html
use strict;
package TLSProxy::ClientHello;
use vars '@ISA';
push @ISA, 'TLSProxy::Message';
sub new
{
my $class = shift;
my ($server,
$data,
$records,
$startoffset,
$message_frag_lens) = @_;
my $self = $class->SUPER::new(
$server,
1,
$data,
$records,
$startoffset,
$message_frag_lens);
$self->{client_version} = 0;
$self->{random} = [];
$self->{session_id_len} = 0;
$self->{session} = "";
$self->{ciphersuite_len} = 0;
$self->{ciphersuites} = [];
$self->{comp_meth_len} = 0;
$self->{comp_meths} = [];
$self->{extensions_len} = 0;
$self->{extension_data} = "";
return $self;
}
sub parse
{
my $self = shift;
my $ptr = 2;
my ($client_version) = unpack('n', $self->data);
my $random = substr($self->data, $ptr, 32);
$ptr += 32;
my $session_id_len = unpack('C', substr($self->data, $ptr));
$ptr++;
my $session = substr($self->data, $ptr, $session_id_len);
$ptr += $session_id_len;
my $ciphersuite_len = unpack('n', substr($self->data, $ptr));
$ptr += 2;
my @ciphersuites = unpack('n*', substr($self->data, $ptr,
$ciphersuite_len));
$ptr += $ciphersuite_len;
my $comp_meth_len = unpack('C', substr($self->data, $ptr));
$ptr++;
my @comp_meths = unpack('C*', substr($self->data, $ptr, $comp_meth_len));
$ptr += $comp_meth_len;
my $extensions_len = unpack('n', substr($self->data, $ptr));
$ptr += 2;
#For now we just deal with this as a block of data. In the future we will
#want to parse this
my $extension_data = substr($self->data, $ptr);
if (length($extension_data) != $extensions_len) {
die "Invalid extension length\n";
}
my %extensions = ();
while (length($extension_data) >= 4) {
my ($type, $size) = unpack("nn", $extension_data);
my $extdata = substr($extension_data, 4, $size);
$extension_data = substr($extension_data, 4 + $size);
$extensions{$type} = $extdata;
}
$self->client_version($client_version);
$self->random($random);
$self->session_id_len($session_id_len);
$self->session($session);
$self->ciphersuite_len($ciphersuite_len);
$self->ciphersuites(\@ciphersuites);
$self->comp_meth_len($comp_meth_len);
$self->comp_meths(\@comp_meths);
$self->extensions_len($extensions_len);
$self->extension_data(\%extensions);
$self->process_extensions();
print " Client Version:".$client_version."\n";
print " Session ID Len:".$session_id_len."\n";
print " Ciphersuite len:".$ciphersuite_len."\n";
print " Compression Method Len:".$comp_meth_len."\n";
print " Extensions Len:".$extensions_len."\n";
}
#Perform any actions necessary based on the extensions we've seen
sub process_extensions
{
my $self = shift;
my %extensions = %{$self->extension_data};
#Clear any state from a previous run
TLSProxy::Record->etm(0);
if (exists $extensions{TLSProxy::Message::EXT_ENCRYPT_THEN_MAC}) {
TLSProxy::Record->etm(1);
}
}
#Reconstruct the on-the-wire message data following changes
sub set_message_contents
{
my $self = shift;
my $data;
my $extensions = "";
$data = pack('n', $self->client_version);
$data .= $self->random;
$data .= pack('C', $self->session_id_len);
$data .= $self->session;
$data .= pack('n', $self->ciphersuite_len);
$data .= pack("n*", @{$self->ciphersuites});
$data .= pack('C', $self->comp_meth_len);
$data .= pack("C*", @{$self->comp_meths});
foreach my $key (keys %{$self->extension_data}) {
my $extdata = ${$self->extension_data}{$key};
$extensions .= pack("n", $key);
$extensions .= pack("n", length($extdata));
$extensions .= $extdata;
if ($key == TLSProxy::Message::EXT_DUPLICATE_EXTENSION) {
$extensions .= pack("n", $key);
$extensions .= pack("n", length($extdata));
$extensions .= $extdata;
}
}
$data .= pack('n', length($extensions));
$data .= $extensions;
$self->data($data);
}
#Read/write accessors
sub client_version
{
my $self = shift;
if (@_) {
$self->{client_version} = shift;
}
return $self->{client_version};
}
sub random
{
my $self = shift;
if (@_) {
$self->{random} = shift;
}
return $self->{random};
}
sub session_id_len
{
my $self = shift;
if (@_) {
$self->{session_id_len} = shift;
}
return $self->{session_id_len};
}
sub session
{
my $self = shift;
if (@_) {
$self->{session} = shift;
}
return $self->{session};
}
sub ciphersuite_len
{
my $self = shift;
if (@_) {
$self->{ciphersuite_len} = shift;
}
return $self->{ciphersuite_len};
}
sub ciphersuites
{
my $self = shift;
if (@_) {
$self->{ciphersuites} = shift;
}
return $self->{ciphersuites};
}
sub comp_meth_len
{
my $self = shift;
if (@_) {
$self->{comp_meth_len} = shift;
}
return $self->{comp_meth_len};
}
sub comp_meths
{
my $self = shift;
if (@_) {
$self->{comp_meths} = shift;
}
return $self->{comp_meths};
}
sub extensions_len
{
my $self = shift;
if (@_) {
$self->{extensions_len} = shift;
}
return $self->{extensions_len};
}
sub extension_data
{
my $self = shift;
if (@_) {
$self->{extension_data} = shift;
}
return $self->{extension_data};
}
sub set_extension
{
my ($self, $ext_type, $ext_data) = @_;
$self->{extension_data}{$ext_type} = $ext_data;
}
sub delete_extension
{
my ($self, $ext_type) = @_;
delete $self->{extension_data}{$ext_type};
}
1;
| openweave/openweave-core | third_party/openssl/openssl/util/TLSProxy/ClientHello.pm | Perl | apache-2.0 | 6,098 |
%<?
% ===================================================================
% File 'e2c_sem.pl'
% Purpose: Attempto Controlled English to CycL conversions from SWI-Prolog
% This implementation is an incomplete proxy for CycNL and likely will not work as well
% Maintainer: Douglas Miles
% Contact: $Author: dmiles $@users.sourceforge.net ;
% Version: 'interface.pl' 1.0.0
% Revision: $Revision: 1.3 $
% Revised At: $Date: 2005/06/06 15:43:15 $
% from Bratko chapter 17 page 455. This comes from Pereira and Warren paper, AI journal, 1980
/*
[14:52] <kinoc> http://turing.cs.washington.edu/papers/yates_dissertation.pdf
[14:54] <kinoc> this was the one I was looking for http://www.cs.washington.edu/homes/soderlan/aaaiSymposium2007.pdf
[15:01] <kinoc> http://www.pat2pdf.org/patents/pat20080243479.pdf while it lasts
% http://danielmclaren.net/2007/05/11/getting-started-with-opennlp-natural-language-processing/
% http://opennlp.sourceforge.net
% http://www.cs.washington.edu/research/textrunner/index.html
*/
% ===================================================================
/*
:-module(e2c_sem, [
e2c_sem/1,
e2c_sem/2,
testE2C/0]).
(SIMPLIFY-CYCL-SENTENCE-SYNTAX ' (#$and
(#$and
(#$isa ?THEY-2
(#$PronounFn #$ThirdPerson-NLAttr #$Plural-NLAttr #$Ungendered-NLAttr #$ObjectPronoun)))
(#$and
(#$and
(#$isa ?THEY-2 Agent-Generic)
(#$and
(#$preActors ?G20477 ?THEY-2)
(#$knows ?THEY-2 ?G57625)))
(#$and
(#$preActors ?G20477 ?THEY-2)
(#$knows ?THEY-2 ?G57625)))))
*/
:- use_module(library(logicmoo_plarkc)).
simplifyCycL(In, Out):- catch((cyclify(In, Mid), evalSubl('SIMPLIFY-CYCL-SENTENCE-SYNTAX'(Mid), Out)), _, fail), !.
simplifyCycL(In, In).
% throwOnFailure/1 is like Java/C's assert/1
throwOnFailure(X):-X, !.
throwOnFailure(X):-trace, not(X).
% imports sentencePos/2, bposToPos/2
%:- style_check(+singleton).
:- style_check(-discontiguous).
:- style_check(-atom).
:- set_prolog_flag(double_quotes, string).
:-set_prolog_flag(double_quotes, string).
:- if(exists_source(cyc)).
:-use_module(cyc).
:-setCycOption(query(time), 2).
:-setCycOption(query(time), 2).
:- cyc:startCycAPIServer.
:- endif.
% imports sentencePos/2, bposToPos/2
:- style_check(-singleton).
:- style_check(-discontiguous).
:- style_check(-atom).
:- set_prolog_flag(double_quotes, string).
:-set_prolog_flag(double_quotes, string).
:- install_constant_renamer_until_eof.
:- set_prolog_flag(do_renames_sumo, never).
:-set_prolog_flag(double_quotes, string).
:-multifile(user:currentParsingPhrase/1).
:-multifile(user:recentParses/1).
:-dynamic(user:recentParses/1).
:-dynamic(user:currentParsingPhrase/1).
:- if(exists_source(cyc)).
:-(ensure_loaded('freq.pdat.txt')).
:-(ensure_loaded('colloc.pdat.txt')).
:-(ensure_loaded('pt-grammar.prul2.txt')).
:-(ensure_loaded('BRN_WSJ_LEXICON.txt')).
:-(consult(textCached)).
:-(consult(recentParses)).
:-(ensure_loaded(logicmoo_nl_pos)).
:-multi_transparent(ac/1).
:-multi_transparent(ac/2).
:-multi_transparent(ac/3).
:-multi_transparent(ac/4).
:-multi_transparent(ac/5).
:-multi_transparent(ac/6).
:-multi_transparent(ac/7).
:-multi_transparent(ac/8).
:-ensure_loaded(owl_parser).
:- endif.
todo(X):-notrace(noteFmt('~q', todo(Agent,X))).
printAndThrow(F, A):-sformat(S, F, A), write(user, S), nl(user), flush_output(user), trace, throw(error(representation_error(S), context(printAndThrow/2, S))).
throwOnFailure(A, _B):-call(A), !.
throwOnFailure(A, B):-printAndThrow('~n ;; Must ~q when ~q ~n', [A, B]).
throwOnFailure(A):-catch(A, E, (printAndThrow('~n ;; ~q Must ~q ~n', [E, A]), !, fail)), !.
throwOnFailure(A):-printAndThrow('~n ;; Must ~q ~n', [A]).
% ===================================================================
% Caches
% ===================================================================
:-dynamic(recentParses/1).
:-dynamic(textCached/2).
saveCaches:-tell(textCached), listing(textCached), told, tell(recentParses), listing(recentParses), told.
:-at_halt(saveCaches).
:-use_module(library(make)), redefine_system_predicate(make:list_undefined).
%:-abolish(make:list_undefined/0).
%make:list_undefined.
%:-abolish(make:list_undefined/1).
%make:list_undefined(_).
%:-abolish(make:list_undefined_/2).
%make:list_undefined_(_Informational, _Local).
%:-abolish(list_undefined_/2).
%list_undefined_(_Informational, _Local).
%:-module_transparent(processRequestHook/1).
%:-multifile(processRequestHook/1).
%:-dynamic(processRequestHook/1).
cmember(H, T):-!, member(H, T).
cmember(H, T):-trace, nonvar(T), T=[H|_].
cmember(H, [_|T]):-nonvar(T), cmember(H, T).
processRequestHook(ARGS):- member(file='english.moo', ARGS), !,
ignore(cmember(english=English, ARGS)),
ignore(English=''),
cyc:writeHTMLStdHeader('English Parser'),
fmt('
<form method="GET">
<p><textarea rows="2" name="english" cols="80">~w</textarea><br>
<input type="submit" value="Parse Normally" name="submit"> <input type="submit" value="Parse with idiomatics" name="submit">
<input type="checkbox" value="CHECKED" name="findall"> Show All<br>
</p>
</form>
<pre>Please wait..
<textarea rows="10" name="debug" cols="80" wrap=off>', [English]),
flush_output,
ignore(once(notrace(e2c_sem(English, CycL)))),
fmt('
</textarea><br>CycL/KIF<br>
<textarea rows="15" name="cycl" cols="80" wrap=off>', []),
flush_output,
once(writeCycL(CycL)),
% notrace(once((cmember(findall='CHECKED', ARGS), ignore(catch(dotimes(34, (e2c_sem(W), nl, nl)), E, writeq(E)))) ; ignore(once(catch(dotimes(1, (e2c_sem(W), nl, nl)), E, writeq(E)))))),
flush_output,
fmt('
</textarea>
..Done
</pre>'),
listRecentParses,
flush_output,
cyc:writeHTMLStdFooter, flush_output, !.
dotimes(N, Goal):- flag('$dotimes', _, N-1),
Goal, flag('$dotimes', D, D-1), D<1.
listRecentParses:-recentParses(Eng), once(listRecentParses(Eng)), fail.
listRecentParses.
listRecentParses(Eng):-
concat_atom(Eng, ' ', EngA),
fmt('<a href="english.moo?english=~w">~w</a><br>', [EngA, EngA]), nl.
% ===================================================================
% Cyc Database normalizer
% ===================================================================
:- if(exists_source(cyc)).
:-use_module(cyc).
%cycQueryV(Vars, CycL):-free_variables(Vars, Free), cyc:cycQueryReal(CycL, 'EverythingPSC', Free, Backchains, Number, Time, Depth).
cycQueryA(CycL):-cycQuery(CycL).
:- endif.
/*
assertion(Result):-assertion(_, _PRED, _, _MT, [Pred|ARGS], _TRUE, _FORWARD, _DEFAULT, _NIL1, _NIL2, _ASSERTEDTRUEDEF, _DATE, _NIL3),
once(assertRefactor(Pred, ARGS, Result)).
*/
assertRefactor(implies, [ARG1, ARG2], Result):-litRefactor([implies, ARG1, ARG2], [implies, LARG1, [Pred|LARG2]]), Result=..[ac, pl_implied, Pred, LARG2, LARG1], !.
assertRefactor(Pred, R1, Out):-litRefactor(R1, R2), Out=..[ac, Pred|R2].
litRefactor(Subj, Subj):- (var(Subj);atom(Subj);number(Subj)), !.
litRefactor([H|T], [HH|TT]):-litRefactor(H, HH), litRefactor(T, TT), !.
litRefactor(var(B, _), B):-!.
litRefactor(B, string(A)):-string(B), string_to_atom(B, S), catch(getWordTokens(S, A), _E, A=B), !.
litRefactor(B, A):-compound(B), B=..BL, litRefactor(BL, AL), A=..AL, !.
litRefactor(B, B).
tas:-tell(a), ignore((assertion(R), fmt('~q.~n', [R]), fail)), told.
:- if(exists_source(el_holds)).
:-ensure_loaded(el_holds).
:-retractall(ac(X, Y, zzzzzzzzzzzzzzzzz)).
:-retractall(ac(X, zzzzzzzzzzzzzzzzz, Y)).
:- endif.
writeCycL(CycL):-
once((toCycApiExpression(CycL, CycL9),
indentNls(CycL9, CycLOutS),
fmt('~w~n', [CycLOutS]), flush_output)), !.
atom_junct(X, Y):-concat_atom(Y, ' ', X).
indentNls(X, S):-string_to_list(X, M), indentNls(0, M, Y), string_to_list(S, Y).
nSpaces(N, []):-N<1, !.
nSpaces(N, [32|More]):-NN is N-1, nSpaces(NN, More), !.
indentNls(_, [], []).
indentNls(N, [40|More], CycLOutS):-NN is N+2, indentNls(NN, More, CycL9), nSpaces(N, Spaces), append([10|Spaces], [40|CycL9], CycLOutS).
indentNls(N, [41|More], [41|CycLOutS]):-NN is N-2, indentNls(NN, More, CycLOutS).
indentNls(N, [X|More], [X|CycLOutS]):-indentNls(N, More, CycLOutS).
noteFmt(F, A):-
dmsg(F, A), !,
%% next two lines if writing to a file will write some debug
current_output(X), !,
(stream_property(X, alias(user_output)) -> true ; (write(X, ' %% DEBUG '), fmt(X, F, A))), !.
sentenceUnbreaker([], []).
sentenceUnbreaker([[W|Ws]|Tagged], [R|ForLGP]):-concat_atom([W|Ws], '_', R), sentenceUnbreaker(Tagged, ForLGP).
sentenceUnbreaker([W|Tagged], [R|ForLGP]):-concat_atom([W], '_', R), sentenceUnbreaker(Tagged, ForLGP).
%getWordTokens("this is English", _Eng).
% string_to_atom(S, 'this is English'), getWordTokens(S, E).
%getWordTokens('this is English', Eng).
% ===================================================================
% Semantic Interpretation
% when using utterance_sem we need to pass 3 arguments,
% the first will match CycL in the head of the DGC clause
% the second is the list containing the words in the utterance_sem
% the third is the empty list.
% ===================================================================
/*
?- e2c_sem("The cat in the hat sees a bat").
(thereExists ?cat65
(and (isa ?cat65 (OneOfFn Cat DomesticCat ) )
(and (and (isa ?sees3 Event ) (thereExists ?bat26
(and (isa ?bat26 (OneOfFn BaseballBat BaseballSwing Bat-Mammal ) )
(or (awareOf ?cat65 ?bat26 ) (and (isa ?sees3 VisualPerception )
(performedBy ?sees3 ?cat65 ) (perceivedThings ?sees3 ?bat26 ) ) ) ) ) )
(thereExists ?hat27 (and (isa ?hat27 Hat ) (in-UnderspecifiedContainer ?cat65 ?hat27 ) ) ) ) ) )
*/
e2c_sem([]):-!.
e2c_sem(''):-!.
e2c_sem(English):-
e2c_sem(English, CycL),
notrace(writeCycL(CycL)), !,
notrace(fmt('~n For sentence: "~w".~n~n', [English])).
e2c_sem(English, CycL9):-nonvar(English),
notrace((noteFmt('~nEnglish: ~q.~n~n', [English]))),
notrace(throwOnFailure(getWordTokens(English, Eng))),
notrace(asserta_if_new(recentParses(Eng))),
e2c_sem(Event, Eng, CycL9), !.
e2c_sem(Event, [], []):-!.
e2c_sem(Event, English, CycL9):-
notrace(noteFmt('~nEng: ~q.~n~n', [English])),
%concat_atom(English, ' ', Text), fmt('~n?- e2c_sem("~w").~n~n', [Text]), flush_output,
notrace(sentenceTagger(English, IsTagged)),
linkParse(English, Links, Tree), writeCycL(Links),
addLinkTags(IsTagged, Links, Tagged),
notrace(dumpList(Tagged)), !,
% time(ignore(catch(e2c_sem(Event, English, Tagged, CycL9), E, (writeCycL(E), ignore(CycL9=error(E)))))),
e2c_sem(Event, English, Tagged, CycL9),
flush_output,
ignore(CycL9=not_parsed(Tagged)),
saveCaches.
p2c(English, CycL):-
notrace(noteFmt('~nEng: ~q.~n~n', [English])),
%concat_atom(English, ' ', Text), fmt('~n?- e2c_sem("~w").~n~n', [Text]), flush_output,
notrace(sentenceTagger(English, IsTagged)),
linkParse(English, Links, Tree), writeCycL(Links),
saveCaches,
addLinkTags(IsTagged, Links, Tagged),
notrace(dumpList(Tagged)), !,
phrase(CycL, Tagged, []),
notrace(writeCycL(CycL)),
notrace(fmt('~n For sentence: "~w".~n~n', [English])).
addLinkTags(Pre, ['S'|Links], Post):-!, addLinkTags(Pre, Links, Post).
%addLinkTags(Pre, Links, Post):-openLists(Pre, Post), !.
addLinkTags(Pre, Links, Post):-Post=Pre, !.
%%addLinkTags(Pre, ['NP'|Links], Post):-getWordSegment(Links, Pre, Segs), addToSegs().
e2c_sem(Event, English, Tagged, CycL):- englishCtx(Event, CycL, Tagged, []).
%e2c_sem(Event, English, Tagged, CycL):- chunkParseCycL(Event, Subj, Tagged, CycL).
%e2c_sem(Event, English, Tagged, no_e2c(English)):-!.
e2c_sem(Event, English, Tagged, no_e2c(List)):-dcgMapCar(Var, theWord(Var), List, Tagged, []).
dcgWordList(List)-->dcgMapCar(Var, theWord(Var), List).
dumpList([]):-nl.
dumpList([B|Tagged]):-dumpList1(B), dumpList(Tagged), !.
dumpList1(Tagged):-writeq(Tagged), nl, flush_output.
%:- setCycOption(cycServer, '10.1.1.3':13701).
cyclifyTest(String, cyc(Result)):-cyc:evalSubL('cyclify'(string(String)), Result).
%cyclifyTest(String, 'cyc-assert'(Result)):-cyc:sublTransaction('10.1.1.3':13701, 'parse-a-sentence-completely'(string(String), '#$RKFParsingMt'), Result).
%cyclifyTest(String, 'cyc-query'(Result)):-cyc:sublTransaction('10.1.1.3':13701, 'parse-a-question-completely'(string(String), '#$RKFParsingMt'), Result).
firstNth1(_Ns, [], []).
firstNth1(Ns, [H|Src], [H|Res]):-Ns>0, N2 is Ns-1, firstNth1(N2, Src, Res).
firstNth1(Ns, Src, []).
lowerOnly([], []):-!.
lowerOnly([[S|H]|T], [[S|H]|TT]):-atom(H), name(H, [A1|_]), is_lower(A1), lowerOnly(T, TT).
lowerOnly([[S|H]|T], TT):-lowerOnly(T, TT).
%sameString(CYCSTRING, String):-var(String), var(CYCSTRING), !, CYCSTRING=String.
%sameString(CYCSTRING, String):-var(CYCSTRING), !, CYCSTRING=String.
reformatStrings(X, X):- (var(X);number(X)), !.
reformatStrings(string(X), S):-string(X), string_to_atom(X, A), reformatStrings(string(A), S).
reformatStrings(string(A), string(S)):-atom(A), !, concat_atom(S, ' ', A).
reformatStrings(X, string(S)):-string(X), string_to_atom(X, S), !.
reformatStrings([], []):-!.
reformatStrings([H|T], [HH|TT]):-!, reformatStrings(H, HH), reformatStrings(T, TT), !.
reformatStrings(X, P):-compound(X), X=..LIST, reformatStrings(LIST, DL), P=..DL, !.
reformatStrings(X, X):-not(atom(X)), !.
reformatStrings(B, A):-atom_concat('#$', A, B), !.
reformatStrings(B, B):-!.
%:-setCycOption(query(time), 2).
% =======================================================
% Text to word info
% =======================================================
harvestCycConstants(DM, DM):-number(DM), !, fail.
harvestCycConstants(Words, DM):-evalSubL(mapcar('#\'cdr', 'denotation-mapper'(string(Words), quote(['#$middleName', '#$alias', '#$initialismString', '#$middleNameInitial', '#$nicknames', '#$givenNames', '#$firstName', '#$abbreviationString-PN']), ':greedy')), List, _), leastOne(List), !, reformatStrings(List, DM), !.
harvestCycConstants(Words, DM):-evalSubL(mapcar('#\'cdr', 'denotation-mapper'(string(Words), quote(['#$middleName', '#$alias', '#$initialismString', '#$middleNameInitial', '#$nicknames', '#$givenNames', '#$firstName', '#$abbreviationString-PN']), ':diligent')), List, _), !, reformatStrings(List, DM), !.
learnTexts([]).
learnTexts([A|B]):-learnText(A), learnTexts(B).
learnText(Atom):-atom(Atom), concat_atom(List, '_', Atom), !, learnText(List).
learnText(X):-textCached(X, [txt|X]), !.
learnText(W):-
saveText(W, [txt|W]),
cyc:fmt(learnText(W)),
ignore((harvestCycConstants(W, CycL), collectionInfo(CycL, COLINFO), saveList(W, COLINFO))),
ignore(makePosInfo(W)),
%denotationInfo(POSINFO, DENOTESINFO),
saveTemplatesForString(W),
ignore((mwStringsForString(W, MWStrings), saveList(W, MWStrings))),
saveCaches.
learnText(W):-!. %true.
saveList(String, []):-!.
saveList(String, [A|List]):-saveText(String, A), saveList(String, List).
saveText(String, A):-asserta_if_new(textCached(String, A)).
appendLists([List], List):-!.
appendLists([L|List], Res):-appendLists(List, AL), append(L, AL, Res), !.
%(#$and (#$speechPartPreds ?Pos ?Pred)(?Pred ?Word ?STRING)
asserta_if_new(X):-retractall(X), asserta(X), !.
asserta_if_new(X):-catch(X, _, fail), !.
asserta_if_new(X):-assertz(X), !.
denotationInfo([], []).
denotationInfo([COL|INFO], [[COL|COLINFO]|MORE]):-
denotationPOS(COL, COLINFO),
denotationInfo(INFO, MORE).
mwStringsForString([N], []):-number(N), !.
mwStringsForString(N, []):-number(N), !.
mwStringsForString(String, []):-!.
mwStringsForString(String, List):-
findall([mwsem, PreText, Word, Pos, THING],
cyc:cycQueryReal(thereExists(Pred,
and(wordForms(Word, Pred, string(String)), speechPartPreds(Pos, Pred),
multiWordString(PreText, Word, Pos, THING))), '#$EnglishMt', [PreText, Word, Pos, THING], 3, 'NIL', 10, 30), List).
wordTerms(Word, List):-
findall([wformulas, Word, Forms],
cyc:cycQueryReal(termFormulas(Word, Forms), '#$EverythingPSC', [Word, Forms], 3, 'NIL', 10, 30), List).
saveTemplatesForString(String):-
wordForString(String, Word, Pos),
saveTemplatesForWord(Word), fail.
saveTemplatesForString(String):-!.
saveTemplatesForWord(Word):-var(Word), !, trace, fail.
saveTemplatesForWord(Word):- textCached(Word, completeSemTrans), !.
saveTemplatesForWord(Word):-
findall([frame, Word, Pos, FRAME, implies(PreRequ, CYCL), Pred],
cycQueryV([Word, Pos, FRAME, CYCL, Pred, PreRequ],
wordSemTrans(Word, _Num, FRAME, CYCL, Pos, Pred, PreRequ)), List), saveList(Word, List), fail.
saveTemplatesForWord(Word):-findall([frame, Word, Pos, FRAME, CYCL, Pred],
cycQueryV([Word, Pos, FRAME, CYCL, Pred], and(isa(Pred, 'SemTransPred'),
semTransPredForPOS(Pos, Pred), arity(Pred, 4), [Pred, Word, _Num, FRAME, CYCL])), List), once(saveList(Word, List)), fail.
saveTemplatesForWord(Word):-findall([frame, Word, 'Verb', FRAME, CYCL, verbSemTrans], cycQueryV([Word, FRAME, CYCL], verbSemTrans(Word, _Num, FRAME, CYCL)), List), once(saveList(Word, List)), fail.
saveTemplatesForWord(Word):-findall([frame, Word, 'Adjective', FRAME, CYCL, adjSemTrans], cycQueryV([Word, FRAME, CYCL], adjSemTrans(Word, _Num, FRAME, CYCL)), List), once(saveList(Word, List)), fail.
saveTemplatesForWord(Word):-
findall([swframe, PreText, Word, FRAME, CYCL, Pos], cycQuery(multiWordSemTrans(PreText, Word, Pos, FRAME, CYCL)), List), saveList(Word, List), fail.
%(denotation Automobile-TheWord CountNoun 0 Automobile)
saveTemplatesForWord(Word):-
findall([denotation, Pos, CYCL], cycQuery(denotation(Word, Pos, _Num, CYCL)), List), saveList(Word, List), fail.
saveTemplatesForWord(Word):-
findall([wsframe, Word, PreText, FRAME, CYCL, Pos], cycQuery(compoundSemTrans(Word, PreText, Pos, FRAME, CYCL)), List), saveList(Word, List), fail.
saveTemplatesForWord(Word):-asserta(textCached(Word, completeSemTrans)).
denotationPOS([lex, COL|Pos], denote(COL)):-!.
/* in POS FILE
wordForString(String, Word, Pos):-atom(String), !, wordForString([String], Word, Pos).
wordForString(String, Word, Pos):-findall(Word, textCached(String, [lex, Word|_]), Words), sort(Words, Words9), !, cmember(Word, Words9).
*/
abbreviationForLexicalWord(S, Pos, Word):-cycQueryV([Pos, Word], abbreviationForLexicalWord(Word, Pos, string(S))).
%getPos(W, Pos, Word):-cycQuery(partOfSpeech(Word, Pos, string(W)), 'GeneralEnglishMt').
%getPos(W, Pred, Word):-cycQueryV([Pred, Word], and(speechPartPreds(Pos, Pred), [Pred, Word, string(W)])).
% sformat(S, '(remove-duplicates (ask-template \'(?Pos ?Word) \'(#$and (#$speechPartPreds ?Pos ?Pred)(?Pred ?Word "~w")) #$EverythingPSC) #\'TREE-EQUAL)', [W]),
% evalSubL(S, R:_).
makePosInfo(String):-getPos(String, Pos, Word), saveText(String, [lex, Word, Pos]), fail.
makePosInfo(String):-!.
%posInfo([W], RR):-atom_concat(NW, '\'s', W), !, wordAllInfoRestart(NW, R), append(R, [[pos, possr_s]], RR).
posInfo(String, [[lex, 'UNKNOWN-Word', 'UNKNOWN-Pos']]):-!.
posInfo2(String, RESFLAT):-findall([Word, Pos], getPos(String, Pos, Word), RES),
findall(Word, cmember([Word, Pos], RES), WRODS), sort(WRODS, WORDS),
posInfo(WORDS, RES, RESFLAT), !.
posInfo([], RES, []):-!.
posInfo([W|WORDS], RES, [[lex, W|POSESS]|RESFLAT]):-findall(Pos, cmember([_Word, Pos], RES), POSES), =(POSES, POSESS),
posInfo(WORDS, RES, RESFLAT).
cycAllIsa([Fort], COLS):-!, cycAllIsa(Fort, COLS).
cycAllIsa(nart(Fort), COLS):-!, cycAllIsa(Fort, COLS).
cycAllIsa(Fort, COLS):-number(Fort), !, findall(Type, numberTypes(Fort, Type), COLS), !.
cycAllIsa(Fort, COLS):-copy_term(Fort, FFort), numbervars(FFort, 0, _), termCyclify(Fort, CycL),
findall(MEMBER, cycQuery('#$or'(nearestIsa(CycL, MEMBER), and(isa(CycL, MEMBER), memberOfList(MEMBER, ['TheList',
'StuffType', 'TemporalObjectType', 'QuantityType', 'GameTypeExceptions',
'SpatialThing-Localized', 'ClarifyingCollectionType', 'Collection', 'Individual', 'Event',
'TemporalStuffType', 'DurativeEventType', 'SituationPredicate', 'ObjectPredicate',
'TruthFunction', 'BinaryRelation', 'UnaryRelation', 'TernaryRelation', 'ObjectPredicate', 'Function-Denotational',
'CollectionType', 'FacetingCollectionType', 'Agent-Generic'])))), COLS).
%cycAllIsa(Fort, COLS):-is_list(Fort), termCyclify(Fort, CycL), cycQueryA(isa(CycL, List)), List, _), reformatStrings(List, COLS).
%cycAllIsa(Fort, COLS):-termCyclify(Fort, CycL), evalSubL('ALL-ISA'((CycL), '#$InferencePSC'), List, _), reformatStrings(List, COLS).
numberTypes(N, 'Integer'):-integer(N).
numberTypes(N, 'Numeral'):-integer(N), N>=0, N<10.
numberTypes(N, 'RealNumber'):-not(integer(N)).
numberTypes(N, 'NegativeNumber'):-N<0.
numberTypes(N, 'PositiveNumber'):-N>0.
numberTypes(N, 'Number-General').
collectionInfo([], []).
collectionInfo([COL|INFO], [[denotation, Pos, COL|COLINFO]|MORE]):-
cycAllIsa(COL, COLINFO),
collectionInfo(INFO, MORE).
% ?- A is rationalize(0.999999999999999), rational(A).
% A = 1000799917193442 rdiv 1000799917193443
subcatFrame(Word, Pos, INT, CAT):-cycQueryA(subcatFrame(Word, Pos, INT, CAT)).
vetodenoteMapper('is', '#$Israel').
theSTemplate(TempType) --> dcgTemplate(TempType, _VarName, _CycL).
theVar(VarName, Subj) --> [_|_], theVar(VarName, Subj), {true}.
theVar(VarName, Subj) --> [].
tellall(X, W):- X, numbervars(X, 0, _), (format('~q.~n', [W])), fail.
tellall(_X, _W):-flush_output.
argName(string(N), Name):-!, atom_concat(':ARG', N, Name).
argName(N, Name):-atom_concat(':ARG', N, Name).
makeArgNameLen(0, []):-!.
makeArgNameLen(N, ArgsS):- N2 is N-1, makeArgNameLen(N2, Args), argName(N, Named), append(Args, [Named], ArgsS).
/*
(genFormat nearestTransitiveNeighbor "~a nearest generalization by transitivity of ~a is ~a"
(TheList
(TheList 2 :EQUALS :POSSESSIVE)
(TheList 1 :EQUALS)
(TheList 3 :EQUALS)))
*/
%tell(pp), rehold, told.
rehold:-between(1, 12, A), functor(P, ac, A),
catch(P, _, fail), once((litRefactor(P, PP), fmt('~q.~n', [PP]))), fail.
rehold.
%getWordTokens(string([X|Y]), [X|Y]):-atom(X), !.
%getWordTokens([X|Y], [X|Y]):-atom(X), !.
%getWordTokens(X, Y):-getCycLTokens(X, Y), !.
% =======================================================
% sentence constituent breaker
% =======================================================
%sentenceChunker(Ws, []):-!.
%linkParse(String, Fourth, P:M):-evalSubL('link-parse'(string(String)), [[P, M, _, string(FourthS)]], _), getSurfaceFromChars(FourthS, Fourth, _).
linkParse(A, XX, B):- linkParse0(A, B, string(Y)), concat_atom(['', S, ''], '"', Y), getSurfaceFromChars(S, XX, YY).
linkParse0(String, FourthS, Fourth):-evalSubL('link-parse'(string(String)), FourthS, _),
append(_, [string(FourthAtom)], FourthS), getSurfaceFromChars(FourthAtom, Fourth, _).
%linkParse(Text, Info, _), !,
sentenceChunker([], []).
sentenceChunker([W|Ws], [New|Out]):-
notrace(isTagChunk(W, Constit)),
gatherChunk(Constit, Ws, NW, Rest),
createChunk(Constit, [W|NW], New),
sentenceChunker(Rest, Out).
createChunk(Constit, WNW, New):-
notrace(getLoc(WNW, Loc)),
notrace(getText(WNW, Text)),
Constit=..List,
append([seg|List], [Text, WNW], Out), !,
New=..Out.
chunkHead(W, Type, RA):-cmember([txt|Text], W), cmember(RA:NGE, W), cmember(1.0-Type, W), !.
gatherChunk(Constit, [], [], []):-!.
gatherChunk(Constit, [W|Ws], [W|SWords], Rest):-
notrace(isTagChunk(W, New)),
chunkCompat(Constit, New), !,
gatherChunk(Constit, Ws, SWords, Rest), !.
gatherChunk(Constit, Rest, [], Rest).
chunkCompat(Start, End):-functor(Start, C, _), functor(End, C, _).
%isTagChunk(W, np('IN')):-getText(W, [of]).
%isTagChunk(W, np('IN')):-getText(W, [for]).
isTagChunk(W, np('PRONOUN')):-getText(W, ['I']).
isTagChunk(W, in('IN')):-isTag(W, 'Preposition'), !.
isTagChunk(W, vp('Modal')):-isTag(W, 'Modal'), !.
isTagChunk(W, vp('AuxVerb')):-isTag(W, 'AuxVerb'), !.
isTagChunk(W, vp('AuxVerb')):-isTag(W, 'BeAux'), !.
isTagChunk(W, vp('AuxVerb')):-isTag(W, 'HaveAux'), !.
isTagChunk(W, wh('WHDeterminer')):-isTag(W, 'WHDeterminer'), !.
isTagChunk(W, wh('WHAdverb, ')):-isTag(W, 'WHAdverb'), !.
isTagChunk(W, cc('CoordinatingConjunction')):-isTag(W, 'cc'), !.
isTagChunk(W, cc('CoordinatingConjunction')):-isTag(W, 'CoordinatingConjunction'), !.
isTagChunk(W, cc('SubordinatingConjunction')):-isTag(W, 'SubordinatingConjunction'), !.
isTagChunk(W, np('POSS')):-isTag(W, 'Possessive'), !.
isTagChunk(W, np('POSS')):-isTag(W, 'PossessivePronoun'), !.
isTagChunk(W, np('PRONOUN')):-isTag(W, 'Pronoun'), !.
isTagChunk(W, np('PROPER')):-isTag(W, 'ProperNoun'), !.
isTagChunk(W, np('DET')):-isTag(W, 'Determiner'), !.
isTagChunk(W, np('Adjective')):-isTag(W, 'Adjective'), !.
isTagChunk(W, np('QUANT')):-isTag(W, 'Quantifier'), !.
isTagChunk(W, vp('Verb')):-isTag(W, 'Verb'), !.
isTagChunk(W, sym('Interjection-SpeechPart')):-isTag(W, 'Interjection-SpeechPart'), !.
isTagChunk(W, sym('SYM')):-isTag(W, '.'), !.
isTagChunk(W, sym('SYM')):-isTag(W, '?'), !.
isTagChunk(W, sym('SYM')):-isTag(W, '!'), !.
isTagChunk(W, sym('SYM')):-isTag(W, '.'), !.
isTagChunk(W, np('COMMON')):-isTag(W, 'nn'), !.
isTagChunk(W, vp('Adverb')):-isTag(W, 'Adverb'), !.
isTagChunk(W, np('OTHER')):-!.
%sentenceParse(Event, Types, Joined):-joinTypes(Types, Joined).
%joinTypes(Types, Joined):- %most of the features i keep off not to violate copywrites .. since the system was designed arround closed src software i had to emulate.. but i hate writting docs which makes me code arround other peoples manuals
/*
TODO These two forms are totally identical?
Mt : EnglishParaphraseMt
(genFormat-Precise hasStoredInside "~a is stored in ~a when not in use"
(TheList 2 1))
genTemplate : (NPIsXP-NLSentenceFn
(TermParaphraseFn-NP :ARG2)
(ConcatenatePhrasesFn
(BestNLPhraseOfStringFn "stored")
(BestPPFn In-TheWord
(TermParaphraseFn-NP :ARG1))))
*/
% =======================================================
% Mining genFormat
% =======================================================
/*
S = '(#$headMedialString "the head-medial string containing ~a, ~a, and ~a is ~a and denotes ~a" (#$TheList 1 (#$TheList 2 :|equals|) 3 (#$TheList 4 :A-THE-WORD) (#$TheList 5 :|equals|)))',
getWordTokens(S, W).
atom_codes("(#$headMedialString \"the head-medial string containing ~a, ~a, and ~a is ~a and denotes ~a\" (#$TheList 1 (#$TheList 2 :|equals|) 3 (#$TheList 4 :A-THE-WORD) (#$TheList 5 :|equals|)))", C), getSurfaceFromChars(C, F, A).
atom_codes("(#$headMedialString \"th ~a\" )", C), tokenize3(C, Ts).
OLD
genFormatH(W1, W2, Reln, [W1, '~a', W2|REst], ArgListL):-cmember(GenFormat, ['genFormat-Precise', 'genFormat']), holdsWithQuery(GenFormat, Reln, String, ArgListL), stringUnify(String, [W1, '~a', W2|REst]).
genFormatH(W1, W2, Reln, ['~a', W1, W2|REst], ArgListL):-cmember(GenFormat, ['genFormat-Precise', 'genFormat']), holdsWithQuery(GenFormat, Reln, String, ArgListL), stringUnify(String, ['~a', W1, W2|REst]).
genFormatH(W1, W2, Reln, [W1, W2|REst], ArgListL):-cmember(GenFormat, ['genFormat-Precise', 'genFormat']), holdsWithQuery(GenFormat, Reln, String, ArgListL), stringUnify(String, [W1, W2|REst]).
genFormatU([W1, W2], DCG, [Reln|Args]):-
genFormatH(W1, W2, Reln, DCGPre, ArgListLC), notrace(cyc:decyclify(ArgListLC, ArgListL)), !,
reformList(ArgListL, ArgList),
% noteFmt('~nArgList: ~q -> ~q:~q ~n', [Reln, DCGPre, ArgList]),
once(dcgRedressGenFormat(0, DCGPre, ArgList, DCG, Vars)), Vars=Vars,
%catch((once(dcgRedressGenFormat(1, DCGPre, ArgList, DCG, Vars)), sort(Vars, VarsS)), E, noteFmt('Error: ~q ~n', [DCGPre])),
once(((getArity(Reln, Arity);length(ArgList, Arity)), number(Arity), makeArgNameLen(Arity, Args))).
*/
genFormatH(Reln, [S|Plit], ArgListL):-cmember(GenFormat, ['genFormat-Precise', 'genFormat']),
holdsWithQuery(GenFormat, Reln, String, ArgListL),
nonvar(String), %%writeq(holdsWithQuery(GenFormat, Reln, String, ArgListL)), nl,
throwOnFailure(nonvar(String)),
once(notrace(stringUnify(String, [S|Plit]))), ignore((cmember('~A', [S|Plit]), trace, writeq(String), stringUnify(String, [_S|_Plit]))).
genFormatU(DCG, [Reln|Args]):-
genFormatH(Reln, DCGPre, ArgListL),
once(reformList(ArgListL, ArgList)),
% noteFmt('~nArgList: ~q -> ~q:~q ~n', [Reln, DCGPre, ArgList]),
once(dcgRedressGenFormat(0, DCGPre, ArgList, DCG, Vars)), Vars=Vars,
%catch((once(dcgRedressGenFormat(1, DCGPre, ArgList, DCG, Vars)), sort(Vars, VarsS)), E, noteFmt('Error: ~q ~n', [DCGPre])),
once(((getArity(Reln, Arity);length(ArgList, Arity)), number(Arity), makeArgNameLen(Arity, Args))).
%dcgRedressGenFormat([DC|GPre], ArgList, DCG, Vars).
replGenFormat(N, varError(N)):-not(ground(N)), !, trace.
replGenFormat([string(['[', ']']), string(['s'])], dcgTrue).
replGenFormat([string(['is']), string(['are'])], dcgTrue).
replGenFormat([string(N)|How], New):-replGenFormat([N|How], New).
replGenFormat([N|How], theGen(Name, How)):-argName(N, Name). %, unSvar(SHow, How).
replGenFormat(N, theGen(Name, [])):-argName(N, Name). %, unSvar(SHow, How).
replGenFormat(N, N):-trace.
% utils
reformList(X, X):-var(X), !.
reformList('TheEmptyList', []):-!.
reformList(X, X):-not(compound(X)), !.
reformList([TheList|ArgList], X):- TheList=='TheList', !, reformList(ArgList, X), !.
reformList([H|T], [HH|TT]):-!, reformList(H, HH), !, reformList(T, TT), !.
reformList(svar(_, B), B):-!.
reformList(B, A):-functor(B, 'TheList', _), B=..BL, reformList(BL, A), !.
reformList(B, A):-B=..BL, reformList(BL, AL), A=..AL, !.
cleanForA(S, [], S):-!.
cleanForA(S, [B-A], SA):-concat_atom(List, B, S), concat_atom(List, A, SA), !.
cleanForA(S, [B-A|More], SA1):-
cleanForA(S, [B-A], SA), cleanForA(SA, More, SA1), !.
stringUnify(S, S):-var(S), trace, !, fail.
stringUnify(S, SU):-var(SU), S=SU, !.
stringUnify([S|H], U):-concat_atom([S|H], ' ', A), !, stringUnify(A, U), !.
stringUnify(string(S), U):-!, stringUnify(S, U), !.
stringUnify(S, U):-atom(S), atom_concat('"', Right, S), atom_concat(New, '"', Right), !, stringUnify(New, U), !.
stringUnify(S, U):-string(S), !, string_to_atom(S, A), !, stringUnify(A, U), !.
stringUnify(S, U):-not(atom(S)), !, trace, fail.
stringUnify(S, U):-cleanForA(S, [
'<br>'-' ',
'\n'-' ',
'\t'-' ',
'~A'-'~a',
'~a'-' ~a ',
(', ')-' , ',
('.')-' . ',
(':')-' : ',
('!')-' ! ',
'('-' ( ',
')'-' ) ',
'['-' [ ',
']'-' ] ',
'{'-' { ',
('}')-(' } '),
('\`')-(' \` '),
('$')-' $ ',
'%'-' % ',
'"'-' " ',
'?'-' ? ',
'\''-' \' ',
% this one breaks it? bug in concat_atom '\\'-' \\ ',
' '-' ',
' '-' ',
'# $ '-'#$'
], SA), concat_atom(U, ' ', SA), !.
stringUnify(S, U):-concat_atom(U, ' ', S), !.
dcgRedressGenFormat(N, A2, ArgList, DCG, varError(N)):-not(ground(ArgList:A2)), !, trace.
dcgRedressGenFormat(N, ['~a'|DCGPre], [How|ArgList], [D|DCG], Vars):-replGenFormat(How, D), N2 is N+1, dcgRedressGenFormat(N2, DCGPre, ArgList, DCG, Vars).
dcgRedressGenFormat(N, ['~a'|DCGPre], ArgList, [theGen(SVAR, [])|DCG], Vars):-N2 is N+1, argName(N2, SVAR), dcgRedressGenFormat(N2, DCGPre, ArgList, DCG, Vars).
%dcgRedressGenFormat(N, ['~a'|DCGPre], [['TheList', Num, Type]|ArgList], [repl(SVAR, Type)|DCG], Vars):-argName(Num, SVAR), dcgRedressGenFormat(N, DCGPre, ArgList, DCG, Vars).
dcgRedressGenFormat(N, [W|DCGPre], ArgList, [theGText([W])|DCG], Vars):-dcgRedressGenFormat(N, DCGPre, ArgList, DCG, Vars).
dcgRedressGenFormat(N, DCG, ArgList, DCG, Vars).
%writeq(ac(comment, 'ScientificNumberFn', string(['(', '#$ScientificNumberFn', 'SIGNIFICAND', 'EXPONENT', ')', denotes, a, number, in, scientific, notation, which, has, 'SIGNIFICAND', with, an, implicit, decimal, point, after, its, first, digit, as, its, significand, and, 'EXPONENT', as, its, exponent, '.', 'So', (', '), e, '.', g, '.', (', '), '(', '#$ScientificNumberFn', 314159, 0, ')', denotes, '3.14159.', 'Likewise', (', '), '(', '#$ScientificNumberFn', 23648762469238472354, 32, ')', denotes, 2.36487624692e+032, or, 2.36487624692, *, 10, ^, 32, '.']))).
genTemplateU(Reln, DCGPre, [Reln|Args]):-
holdsWithQuery(genTemplate, Reln, DCGPre),
once((getArity(Reln, Arity), number(Arity), makeArgNameLen(Arity, Args))).
/*
%todo
getGenFormat(PredType, _Template, ARGS):-
holdsWithQuery(genFormat, Pred, string(Str), How), %getPredType(Pred, PredType, Arity),
genArgList(1, PredType, Arity, How, Str, StrFmt, ARGS).
%genArgList(N, How, Str, StrFmt, ARGS):-
*/
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%55
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%55
getPredType(Pred, 'Predicate', 2):-holdsWithQuery(isa, Pred, 'BinaryPredicate'), !.
getPredType(Pred, 'Function', 2):-holdsWithQuery(isa, Pred, 'BinaryFunction'), !.
getPredType(Pred, 'Function', A):-atom(Pred), atom_codes(Pred, [C|_]), is_upper(C), getArity(Pred, A), number(A), !.
getPredType(Pred, 'Predicate', A):-atom(Pred), atom_codes(Pred, [C|_]), is_lower(C), getArity(Pred, A), number(A), !.
getArity(Pred, A):-holdsWithQuery(arity, Pred, A), (number(A) -> ! ; true).
getArity(Pred, Out):-holdsWithQuery(arityMin, Pred, A), (number(A) -> (! , Out is A + 0 ); Out=A).
getArity(Pred, Out):-(noteFmt('CANT get arity of ~q ~n', [Pred])), !, atom(Pred), Out=1.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%55
holdsWithQuery(Reln, DCGPre, CycLPre):-Reln == expansion, catch(cycQuery([Reln, DCGPre, CycLPre], 'EverythingPSC'), _, fail).
holdsWithQuery(Reln, DCGPre, CycLPre):-ac(Reln, DCGPre, CycLPre).
holdsWithQuery(Reln, DCGPre, CycLPre):-Reln \== expansion, catch(cycQuery([Reln, DCGPre, CycLPre], 'EverythingPSC'), _, fail).
holdsWithQuery(Reln, TempType, DCGPre, CycLPre):-ac(Reln, TempType, DCGPre, CycLPre).
holdsWithQuery(Reln, TempType, DCGPre, CycLPre):-cycQuery([Reln, TempType, DCGPre, CycLPre], 'EverythingPSC').
holdsWithQuery(Reln, TempType, Name, DCGPre, CycLPre):-ac(Reln, TempType, Name, DCGPre, CycLPre).
holdsWithQuery(Reln, TempType, Name, DCGPre, CycLPre):-cycQuery([Reln, TempType, Name, DCGPre, CycLPre], 'EverythingPSC').
holdsWithQuery(Reln, TempType, Name, DCGPre, CycLPre, Test):-ac(Reln, TempType, Name, DCGPre, CycLPre, Test).
holdsWithQuery(Reln, TempType, Name, DCGPre, CycLPre, Test):-cycQuery([Reln, TempType, Name, DCGPre, CycLPre, Test], 'EverythingPSC').
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%55
% =======================================================
% Mine out Cyc idiomatic DCGs
% =======================================================
:-dynamic(cache_dcgRedressStart/4).
list_dcgRedressStart :- cache_dcgRedressStart(Reln, DCGPre, DCG, Vars),
numbervars(cache_dcgRedressStart(Reln, DCGPre, DCG, Vars), 0, _),
noteFmt('?- ~q. ~n ', [dcgRedressStart(Reln, DCGPre, DCG, Vars)]), fail.
list_dcgRedressStart :- retractall(cache_dcgRedressStart(_, _, _, _)).
dcgRedressStart(Reln, DCGPre, DCG, VarsO):-
nonvar(DCGPre),
asserta(cache_dcgRedressStart(Reln, DCGPre, DCG, Vars)),
catch((dcgRedress(DCGPre, DCG, Vars), sort(Vars, VarsO)), E,
(printAndThrow('Error: ~q in ~q/~q ~q ~n', [E, DCG, Vars, DCGPre]), list_dcgRedressStart, trace)),
retractall(cache_dcgRedressStart(_, _, _, _)).
% todo fix ac('genTemplate-Constrained', subsetOf, [and, [isa, svar(_G276, ':ARG1'), 'Collection'], [isa, svar(_G291, ':ARG2'), 'Collection']], ['NPIsNP-NLSentenceFn', ['PhraseFormFn', singular, ['ConcatenatePhrasesFn', ['BestNLPhraseOfStringFn', string([the, set, of, all])], ['TermParaphraseFn-Constrained', 'nonSingular-Generic', svar(_G276, ':ARG1')]]], ['IndefiniteNounPPFn', 'Subset-TheWord', string([of]), ['ConcatenatePhrasesFn', ['BestNLPhraseOfStringFn', string([the, set, of, all])], ['TermParaphraseFn-Constrained', 'nonSingular-Generic', svar(_G291, ':ARG2')]]]]).
dcgt :- dcgRedress( ['NPIsNP-NLSentenceFn', ['PhraseFormFn', singular, ['ConcatenatePhrasesFn', ['BestNLPhraseOfStringFn', string([the, set, of, all])], ['TermParaphraseFn-Constrained', 'nonSingular-Generic', svar(_G276, ':ARG1')]]], ['IndefiniteNounPPFn', 'Subset-TheWord', string([of]), ['ConcatenatePhrasesFn', ['BestNLPhraseOfStringFn', string([the, set, of, all])], ['TermParaphraseFn-Constrained', 'nonSingular-Generic', svar(_G291, ':ARG2')]]]], DCG, Vars).
dcgt(DCG, Vars) :- dcgRedress( ['NPIsNP-NLSentenceFn', ['PhraseFormFn', singular, ['ConcatenatePhrasesFn', ['BestNLPhraseOfStringFn', string([the, set, of, all])], ['TermParaphraseFn-Constrained', 'nonSingular-Generic', svar(_G276, ':ARG1')]]], ['IndefiniteNounPPFn', 'Subset-TheWord', string([of]), ['ConcatenatePhrasesFn', ['BestNLPhraseOfStringFn', string([the, set, of, all])], ['TermParaphraseFn-Constrained', 'nonSingular-Generic', svar(_G291, ':ARG2')]]]], DCG, Vars).
mustNonvar(Vars, Call):-call(Call), once(nonvar(Vars);(noteFmt('mustNonvar ~q~n', [Call]), flush, trace)).
appliedTemplate_mine('GenerationPhrase', Reln, DCG, CycL9):-
genFormatU(DCGPre, [Reln|Args]),
dcgRedressStart([Reln|Args], DCGPre, DCG, VarsS),
once(cyclRedress([Reln|Args], CycL)), substEach(CycL, VarsS, CycL9).
appliedTemplate_mine(TempType, Reln, DCG, CycL9):-
cmember(Reln, ['assertTemplate', 'rewriteTemplate', 'termTemplate', 'queryTemplate', 'commandTemplate']),
holdsWithQuery(Reln, TempType, DCGPre, CycLPre),
dcgRedressStart(CycLPre, DCGPre, DCG, VarsS),
once(cyclRedress(CycLPre, CycL)), substEach(CycL, VarsS, CycL9).
appliedTemplate_mine(TempType, Reln:Name, DCG, CycL9):-
cmember(Reln, ['assertTemplate-Reln', 'metaStatementTemplate-Reln', 'termTemplate-Reln', 'queryTemplate-Reln', 'commandTemplate-Reln']),
holdsWithQuery(Reln, TempType, Name, DCGPre, CycLPre),
dcgRedressStart(Name-CycLPre, DCGPre, DCG, VarsS),
once(cyclRedress(CycLPre, CycL)), substEach(CycL, VarsS, CycL9).
appliedTemplate_mine(TempType, Reln:Name, DCG, CycL9):-
cmember(Reln, ['assertTemplate-Test', 'termTemplate-Test', 'queryTemplate-Test']),
holdsWithQuery(Reln, TempType, Name, DCGPre, CycLPre, Test),
dcgRedressStart(implies(Test, CycLPre), DCGPre, DCG, VarsS),
once(cyclRedress(implies(Test, CycLPre), CycL)), substEach(CycL, VarsS, CycL9).
appliedTemplate_mine('GenerationTemplateConstrained', Reln, DCG, CycL9):-
holdsWithQuery('genTemplate-Constrained', Reln, Constr, DCGPre), nonvar(DCGPre),
once((getArity(Reln, Arity), number(Arity), makeArgNameLen(Arity, Args))),
dcgRedressStart([Reln|Args], DCGPre, DCG, VarsS),
once(cyclRedress(implies(Constr, [Reln|Args]), CycL)), substEach(CycL, VarsS, CycL9).
appliedTemplate_mine('GenerationTemplate', Reln, DCG, CycL9):-
genTemplateU(Reln, DCGPre, [Reln|Args]), nonvar(DCGPre), CycLPre=[Reln|Args],
dcgRedressStart([Reln|Args], DCGPre, DCG, VarsS),
once(cyclRedress(CycLPre, CycL)), substEach(CycL, VarsS, CycL9).
tl:-told,
tell('dcgTermTemplate.pl'),
tellall(appliedTemplate_mine(TempType, Reln, DCG, CycL9), appliedTemplate(TempType, Reln, DCG, CycL9)), told.
:- if(exists_source(dcgTermTemplate)).
:- ensure_loaded(dcgTermTemplate).
:- endif.
:- if(exists_source(dcgTermTemplate2)).
:- ensure_loaded(dcgTermTemplate2).
:- endif.
isCycKeyword(KW):-atom(KW), atom_concat(':', _, KW).
getKeyVariable(KW, KW):-isCycKeyword(KW), !.
getKeyVariable(KW, KW):-atom(KW), !, atom_concat('?', _, KW), !.
getKeyVariable(SVAR, KW):-nonvar(SVAR), SVAR = svar(_, KW), !.
getKeyVariable(SVAR, KW):-nonvar(SVAR), !, SVAR = [svar, _, KW].
getKeyVariable(SVAR, KW):-sformat(S, ':VAR~w', [SVAR]), string_to_atom(S, KW), !, noteFmt(';; ~q.~n', [getKeyVariable(SVAR, KW)]), list_dcgRedressStart. %, ignore(KW=SVAR).
cyclRedress(V, V):-var(V), !.
cyclRedress(svar(_, VarName), VarName):-!.
cyclRedress([Cyc|L], [CycO|LO]):-cyclRedress(Cyc, CycO), cyclRedress(L, LO), !.
cyclRedress(CycL, CycL9):-compound(CycL), !, CycL=..[Cyc|L], cyclRedress([Cyc|L], CycLL), CycL9=..CycLL, !.
cyclRedress(CycL, CycL):-!.
juntifyList(Pred, List, Res):-!, delete(List, theGText(['']), List1), delete(List1, theGText(''), List2), juntifyList0(Pred, List2, Res), !.
juntifyList0(Pred, [], Pred):-!.
juntifyList0(dcgSeq, [List], List):-!.
%juntifyList0(Pred, [List], Res):-!, Res=..[Pred, List], !.
juntifyList0(Pred, [H|List], Res):-length([H|List], Len), Res=..[Pred, Len, [H|List]], !.
juntifyList0(Pred, [H|List], Res):-juntifyList0(Pred, List, PRES), Res=..[Pred, H, PRES], !.
dcgRedressJunctify(DcgSeq, List, DCG, Vars):- throwOnFailure((dcgRedressL(List, RList, Vars), juntifyList(DcgSeq, RList, DCG))),
throwOnFailure(nonvar(DCG), dcgRedressJunctify(DcgSeq, List, DCG, Vars)), !.
dcgRedressL(I, O, V):-debugOnFailure(dcgRedressL0(I, O, V)), throwOnFailure(nonvar(O), dcgRedressJunctify(DcgSeq, List, DCG, Vars)), !.
dcgRedressL0([], [], []):-!.
dcgRedressL0([H|T], HHTT, Vars):-dcgRedressSafe(H, HH, Var1), !, dcgRedressL0(T, TT, Var2), append(Var1, Var2, Vars), !, HHTT=[HH|TT].
dcgRedressSafe(H, HH, Var1):-throwOnFailure((dcgRedress(H, HH, Var1))), throwOnFailure((nonvar(HH), nonvar(Var1)), dcgRedressSafe(H, HH, Var1)).
% dcgRedress(A, B, C):-trace, throw(dcgRedress(A, B, C)).
dcgRedress(V, theVar(KW, V), []):-var(V), !, getKeyVariable(V, KW), !, list_dcgRedressStart.
dcgRedress(Var, A, B):-var(Var), trace, !, printAndThrow('dcgRedress got var in arg1 ~q', [dcgRedress(Var, A, B)]).
dcgRedress(A, NonVar, B):-nonvar(NonVar), trace, !, printAndThrow('dcgRedress got nonvar in arg2 ~q ', [dcgRedress(A, NonVar, B)]).
dcgRedress(A, B, NonVar):-nonvar(NonVar), trace, !, printAndThrow('dcgRedress got nonvar in arg3 ~q ', [dcgRedress(A, B, NonVar)]).
dcgRedress(V, varError(V), []):-var(V), !, trace, !. %, throw(error(dcgRedress/3, 'Arguments are not sufficiently instantiated'))
dcgRedress(X, S, Vars):-string(X), string_to_atom(X, A), dcgRedress_string(A, S, Vars).
dcgRedress(DCG, theGText(DCG), []):-number(DCG), !.
dcgRedress([Var|Rest], varError([Var|Rest]), []):-
var(Var),
noteFmt('Var in head of list: ~w~n', [[Var|Rest]]),
list_dcgRedressStart, trace.
dcgRedress(string(S), A, Vars):-!, dcgRedress_string(S, A, Vars).
dcgRedress([string, S], A, Vars):-!, dcgRedress_string(S, A, Vars).
dcgRedress_string((string(String)), DCG, Var):-!, dcgRedress_string(String, DCG, Var).
dcgRedress_string([string, String], DCG, Var):-!, dcgRedress_string(String, DCG, Var).
dcgRedress_string([string|String], DCG, Var):-!, dcgRedress_string(String, DCG, Var).
dcgRedress_string(X, S, Vars):-string(X), string_to_atom(X, A), dcgRedress_string(A, S, Vars).
dcgRedress_string(([DCG]), theGText(DCG), []):-!.
dcgRedress_string((""), dcgNone, []):-!.
dcgRedress_string((''), dcgNone, []):-!.
dcgRedress_string((String), DCG, Vars):-atom(String), atom_concat('"', Right, String), atom_concat(New, '"', Right), dcgRedress_string(New, DCG, Vars), !.
dcgRedress_string((String), DCG, Vars):-atom(String), concat_atom([H, T|List], ' ', String), !, dcgRedress_string([H, T|List], DCG, Vars), !.
dcgRedress_string((String), theGText(A), []):-atom(String), cleanEachAtomList(String, A), !, (atom(A)->throwOnFailure(atom_codes(A, [_|_]));throwOnFailure(A=[_|_])).
dcgRedress_string(([D|CG]), theText(DCG), []):-throwOnFailure(cleanEachAtomList([D|CG], DCG)), noteFmt('~q.~n', theText(DCG)), !, list_dcgRedressStart.
dcgRedress(D, DCG, Vars):-string(D), !, dcgRedress(string(D), DCG, Vars), !.
dcgRedress(String, DCG, Var):-atom(String), atom_concat('"', _, String), !, dcgRedress(string(String), DCG, Var), !.
dcgRedress(TemplateMarker, DCG, Vars):-templateMarkerRepresentation(TemplateMarker, Char), !, dcgRedress(string(Char), DCG, Vars), !.
dcgRedress([TemplateMarker], DCG, Vars):-templateMarkerRepresentation(TemplateMarker, Char), !, dcgRedress(string(Char), DCG, Vars), !.
cleanEachAtomList(B, AA):-cleanEachAtom(B, A), (is_list(A)->delete(A, '', AA);AA=A).
cleanEachAtom([], []):-!.
cleanEachAtom([svar|S], [svar|S]):-!, trace.
cleanEachAtom(['\'', OneTwo|CG], ['\''|CG2]):-atom(OneTwo), atom_length(OneTwo, N), N>0, N<3, !,
cleanEachAtom([OneTwo|CG], CG2), !.
cleanEachAtom([D|CG], CG2):- cleanEachAtom(D, D2), D2='\'', !, cleanEachAtomList(CG, CG2), !.
cleanEachAtom([D|CG], [D2|CG2]):-!,
cleanEachAtom(D, D2), !,
cleanEachAtomList(CG, CG2), !.
cleanEachAtom(D, A):-string(D), string_to_atom(D, M), !, cleanEachAtom(M, A), !.
cleanEachAtom(D, A):-not(atom(D)), !, (D=A->true;trace).
cleanEachAtom(D, D):-atom_codes(D, [_]), !.
cleanEachAtom(D, A):-atom_concat('\\"', M, D), M\='', cleanEachAtom(M, A), !.
cleanEachAtom(D, A):-atom_concat(M, '\\"', D), M\='', cleanEachAtom(M, A), !.
cleanEachAtom(D, A):-atom_concat(M, '\\', D), cleanEachAtom(M, A), !.
cleanEachAtom(D, A):-atom_concat('\\', M, D), cleanEachAtom(M, A), !.
cleanEachAtom(D, A):-atom_concat('\'', M, D), cleanEachAtom(M, A), !.
cleanEachAtom(D, A):-atom_concat(M, '\'', D), cleanEachAtom(M, A), !.
cleanEachAtom(D, A):-atom_concat('"', M, D), cleanEachAtom(M, A), !.
cleanEachAtom(D, A):-atom_concat(M, '"', D), cleanEachAtom(M, A), !.
cleanEachAtom(A, A).
dcgRedress(['theGText'([Word])], DCG, Vars):-dcgRedress_string(Word, DCG, Vars), !.
dcgRedress(['theGText'(Word)], DCG, Vars):-dcgRedress_string(Word, DCG, Vars), !.
dcgRedress(['theGText'|Word], DCG, Vars):-dcgRedress_string(Word, DCG, Vars), !.
dcgRedress(['theGen', VarName, []], dcgTemplate('AnyTemplate', VarNameO, Subj), [VarNameO-Subj]):-getKeyVariable(VarName, VarNameO), !.
dcgRedress(['theGen', VarName, Details], dcgTemplateKW(Details, VarNameO, Subj), [VarNameO-Subj]):-getKeyVariable(VarName, VarNameO), !.
dcgRedress(svar(Subj, VarName), theVar(VarName, Subj), [VarName-Subj]):-!, noteFmt('~q~n', [theVar(VarName, Subj)]), list_dcgRedressStart.
dcgRedress(['OptionalSome'|List], dcgOptionalSome(RList), Vars):-dcgRedressL(List, RList, Vars), !.
dcgRedress(['OPTIONALSOME'|List], dcgOptionalSome(RList), Vars):-dcgRedressL(List, RList, Vars), !.
dcgRedress(['OptionalOne'|List], dcgOptionalOne(RList), Vars):-dcgRedressL(List, RList, Vars), !.
dcgRedress(['NLPatternList'|List], DCG, Vars):-!, dcgRedressJunctify(dcgSeq, List, DCG, Vars), !.
dcgRedress(['NLPattern-Exact'|List], DCG, Vars):-!, dcgRedressJunctify(dcgSeq, List, DCG, Vars), !.
dcgRedress(['RequireOne'|List], DCG, Vars):-dcgRedressJunctify(dcgOr, List, DCG, Vars), !.
dcgRedress(['RequireSome'|List], DCG, Vars):-dcgRedressJunctify(dcgRequireSome, List, DCG, Vars), !.
dcgRedress(['WordSequence'], dcgNone, []):-!.
dcgRedress('WordSequence', dcgNone, []):-!.
dcgRedress(['WordSequence'|List], DCG, Vars):-dcgRedressJunctify(dcgSeq, List, DCG, Vars), !.
dcgRedress(['NLPattern-Word', Word, Pos], thePOS(Word, Pos), []):-!.
dcgRedress(['NLPattern-Term', Term, Pos], dcgAnd(thePOS(Pos), theTerm(Term)), []):-!.
dcgRedress(['TermPOSPair', Term, Pos], dcgAnd(thePOS(Pos), theTerm(Term)), []):-!.
dcgRedress(['NLPattern-TermPred', Term, Pos], theTermPred(Term, Pos), []):-!.
dcgRedress(['NLPattern-Template', TempType, VarName], dcgTemplate(TempType, VarNameO, Subj), [VarNameO-Subj]):-getKeyVariable(VarName, VarNameO), !.
dcgRedress(['NLPattern-POS', VarName, Pos], dcgPosVar(Pos, VarNameO, Subj), [VarNameO-Subj]):-getKeyVariable(VarName, VarNameO), !.
dcgRedress(['NLPattern-Agr', VarName, Pos], dcgPosVar(Pos, VarNameO, Subj), [VarNameO-Subj]):-getKeyVariable(VarName, VarNameO), !.
dcgRedress(['WordWithSuffixFn', Word, Suffix], theWord(['WordWithSuffixFn', Word, Suffix]), []):-!.
dcgRedress(['BestNLPhraseOfStringFn', VarName], dcgTemplate('AnyTemplate', VarNameO, Subj), [VarNameO-Subj]):-getKeyVariable(VarName, VarNameO), !.
dcgRedress(['BestNLPhraseOfStringFn', VarName], dcgTemplate('AnyTemplate', VarName, Subj), [VarName-Subj]):-var(VarName), trace, !.
dcgRedress(['BestNLPhraseOfStringFn', string(String)], DCG, Var):-!, dcgRedress(string(String), DCG, Var), !.
dcgRedress(['BestNLPhraseOfStringFn', String], DCG, Var):-!, dcgRedress(string(String), DCG, Var), !.
dcgRedress(['BestNLWordFormOfLexemeFn', Word], theWord(Word), []):-!.
dcgRedress(['BestHeadVerbForInitialSubjectFn', Word], theWord(Word), []):-!.
dcgRedress(['HeadWordOfPhraseFn', Word], Out, Vars):-!, dcgRedress(Word, Out, Vars), !.
dcgRedress(['BestSymbolPhraseFn', Word], dcgOr(theWord(Word), theTermStrings(Word)), []):-!.
dcgRedress(['ConcatenatePhrasesFn-NoSpaces'|List], dcgNoSpaces(DCG), Vars):-dcgRedressJunctify(dcgSeq, List, DCG, Vars), !.
dcgRedress(['ConcatenatePhrasesFn'|List], DCG, Vars):-dcgRedressJunctify(dcgSeq, List, DCG, Vars), !.
dcgRedress(['TermParaphraseFn-NP', VarName], dcgTemplate('NPTemplate', VarNameO, Subj), [VarNameO-Subj]):-getKeyVariable(VarName, VarNameO), !.
% this makes a new arg
dcgRedress(['TermParaphraseFn-NP', Constr], dcgAnd(dcgTemplate('NPTemplate', VarNameO, Subj), isPOS(Constr)), [VarNameO-VarName]):-getKeyVariable(VarName, VarNameO), !.
dcgRedress(['StringMentionFn', VarName], dcgTemplate('StringTemplate', VarNameO, Subj), [VarNameO-Subj]):-getKeyVariable(VarName, VarNameO), !.
dcgRedress(['PercentParaphraseFn', VarName], dcgTemplate('PercentTemplate', VarNameO, Subj), [VarNameO-Subj]):-getKeyVariable(VarName, VarNameO), !.
dcgRedress(['TermParaphraseFn-Possessive', VarName], dcgTemplate('PossessiveTemplate', VarNameO, Subj), [VarNameO-Subj]):-getKeyVariable(VarName, VarNameO), !.
dcgRedress(['QuotedParaphraseFn'|List], dcgMaybeQuoted(DCG), Vars):-dcgRedressJunctify(dcgSeq, List, DCG, Vars), !.
%% TODO these need more work
dcgRedress(['TermParaphraseFn', VarName], dcgTemplate('AnyTemplate', VarNameO, Subj), [VarNameO-Subj]):-getKeyVariable(VarName, VarNameO), !.
dcgRedress(['TermParaphraseFn', [KW|List]], DCG, Vars):-getKeyVariable(KW, _VarNameO), dcgRedressJunctify(dcgSeq, [['TermParaphraseFn', _VarNameO]|List], DCG, Vars), !.
dcgRedress(['TermParaphraseFn'], varError('TermParaphraseFn'), []):- trace, !.
dcgRedress(['TermParaphraseFn' |List], DCG, Vars):- dcgRedressJunctify(dcgSeq, List, DCG, Vars), !.
%dcgRedress(['TermParaphraseFn', VarName], dcgInverse(VarName), []):-!.
dcgRedress(['BestCycLPhraseFn', VarNameO], dcgCycL(Subj, VarNameO), [VarNameO-Subj]):-getKeyVariable(VarName, VarNameO), !.
dcgRedress(['TermParaphraseFn-Constrained', Pos, VarName], dcgPosVar(Pos, VarNameO, Subj), [VarNameO-Subj]):-atom( Pos), getKeyVariable(VarName, VarNameO), !.
dcgRedress(['TermParaphraseFn-Constrained', Constr, List], dcgConstraintBindings(DCG, Constr), Vars):-dcgRedress(List, DCG, Vars), !.
dcgRedress(['BestNLWordFormOfLexemeFn-Constrained', Pos, Word], thePOS(Word, Pos), []):-atom( Pos), atom(Word), !.
dcgRedress(['ConditionalPhraseFn', Constr|List], dcgConstraint(DCG, Constr), Vars):-!, dcgRedressJunctify(dcgSeq, List, DCG, Vars), !.
% dcgSeqReinterp
dcgRedress(['BestBindingsPhraseFn', Constr, List], dcgConstraintBindings(DCG, Constr), Vars):-nonvar(List), dcgRedress(List, DCG, Vars), !.
dcgRedress(['BestBindingsPhraseFn'|ConstrList], Foo, Bar):-true, !, ignore(Foo=dcgConstraintBindings(ConstrList)), ignore(Bar=[]).
dcgRedress(['RepeatForSubsequentArgsFn', Num, List], dcgRepeatForSubsequentArgsFn(Num, DCG), Vars):-dcgRedress(List, DCG, Vars), !.
dcgRedress(['BestChemicalFormulaFn', List, Counts], dcgBestChemicalFormulaFn(DCG, Counts), Vars):-dcgRedress(List, DCG, Vars), !.
dcgRedress(VarName, dcgTemplate('AnyTemplate', VarNameO, Subj), [VarNameO-Subj]):-getKeyVariable(VarName, VarNameO), !.
dcgRedress(['BestDetNbarFn'|List], DCG, Vars):-!, dcgRedressJunctify(dcgSeq, List, DCG, Vars), !.
dcgRedress(['BestDetNbarFn-Indefinite'|List], dcgPhraseType('BestDetNbarFn-Indefinite', DCG), Vars):-!, dcgRedressJunctify(dcgSeq, List, DCG, Vars), !.
dcgRedress(['BestDetNbarFn-Definite'|List], dcgPhraseType('BestDetNbarFn-Definite', DCG), Vars):-!, dcgRedressJunctify(dcgSeq, List, DCG, Vars), !.
dcgRedress(['TypeClarifyingPhraseFn', NP, COMP], dcgSeq(dcgOptional(dcgOptional(theWord('The-TheWord')), DCG1, dcgOptional(theWord('Of-TheWord'))), DCG2), Vars):-!,
dcgRedress(NP, DCG1, Vars1), dcgRedress(COMP, DCG2, Vars2), append(Vars1, Vars2, Vars), !.
dcgRedress(['BestPPFn', A, B], dcgSeq(theWord(A, 'Preposition'), DCG2), Vars):-!, dcgRedress(B, DCG2, Vars), !.
dcgRedress(['BestPPFn'|List], DCG, Vars):-!, dcgRedressJunctify(dcgSeq, List, DCG, Vars), !.
dcgRedress(['NPIsXP-NLSentenceFn', NP, COMP], dcgSeq(DCG1, theWord('Be-TheWord'), DCG2), Vars):-!,
dcgRedress(NP, DCG1, Vars1), dcgRedress(COMP, DCG2, Vars2), append(Vars1, Vars2, Vars), !.
% ['DefiniteNounPPFn', 'Government-TheWord', '"of"', ['TermParaphraseFn-NP', ':ARG1']]
dcgRedress(['DefiniteNounPPFn'|List], dcgPhraseType('DefiniteNounPPFn', DCG), Vars):-!, dcgRedressJunctify(dcgSeq, List, DCG, Vars), !.
dcgRedress(['PhraseFormFn', Pos, Template], dcgAnd(thePOS(Pos), DCG), Vars):-!, dcgRedress(Template, DCG, Vars), !.
dcgRedress(['BestVerbFormForSubjectFn', Word, NOTE], dcgAnd(thePOS(Word, 'Verb'), dcgNote(NOTE)), []):-!.
dcgRedress(['GenTemplateRecipeOmitsArgFn', Arg, Template], dcgAnd(DCG, dcgNote('GenTemplateRecipeOmitsArgFn'(Arg))), Vars):-dcgRedress(Template, DCG, Vars), !.
dcgRedress(['NPTemplate', VarName], dcgTemplate('NPTemplate', VarName, Subj), [VarName-Subj]):-!.
dcgRedress(['PossessiveTemplate', VarName], dcgTemplate('PossessiveTemplate', VarName, Subj), [VarName-Subj]):-!.
dcgRedress(['NBarTemplate', VarName], dcgTemplate('NBarTemplate', VarName, Subj), [VarName-Subj]):-!.
dcgRedress([TemplateType, VarName], dcgTemplate(TemplateType, VarName, Subj), [VarName-Subj]):-
atom(TemplateType), debugOnError(cycQuery(genls(TemplateType, 'ParsingTemplateCategory'))), !.
dcgRedress(['NLConjunctionFn'|List], DCG, Vars):-!, throwOnFailure((dcgRedressL(List, RList, Vars), juntifyList(dcgConjWithWord, ['And-TheWord', RList], DCG))), !.
dcgRedress(['NLDisjunctionFn'|List], DCG, Vars):-!, throwOnFailure((dcgRedressL(List, RList, Vars), juntifyList(dcgConjWithWord, ['Or-TheWord', RList], DCG))), !.
dcgRedress(THEWORD, theWord(THEWORD), []):-atom(THEWORD), atom_concat(_, '-TheWord', THEWORD), !.
isNLFunction(NL):-not(atom(NL)), !, fail.
isNLFunction(NL):-concat_atom([_, 'NL', _], '', NL), !.
isNLFunction('NPIsNP-NLSentenceFn'):-!.
isNLFunction(NL):-cycQueryIsaCache(NL, 'NLFunction').
:-dynamic(notIsaIC/2).
cycQueryIsaCache(I, C):-notIsaIC(I, C), !, fail.
cycQueryIsaCache(I, C):-catch(holdsWithQuery(isa, I, C), _, fail), !.
cycQueryIsaCache(I, C):-asserta(notIsaIC(I, C)), !, fail.
% Term to List
dcgRedress(DCG, DOIT, Vars):-not(DCG=[_|_]), compound(DCG), pterm_to_sterm(DCG, DCGL), (nonvar(DCGL);trace), !, dcgRedress(DCGL, DOIT, Vars), !.
%dcgRedress(DCG, Out, Vars):-notrace(once(cyc:decyclify(DCG, UDCG))), (DCG\== UDCG), !, throwOnFailure(dcgRedress(UDCG, Out, Vars)), !.
isSomeFn(X):-nonvar(X), cmember(X, ['SomeFn', 'AnyFn', 'GovernmentFn', 'EveryFn', 'ManyFn', 'CollectionSubsetFn', 'FormulaArgFn', 'SpecsFn']).
isSomeFn(X):-atom(X), atom_concat('SubcollectionOf', _, X).
isSomeFn(X):-atom(X), concat_atom(['Collection', _, 'Fn'], '', X).
dcgRedress([SomeFn, Var|Rest], dcgAnd(dcgReverse([SomeFn, VarNameO|Rest]), theVar(Var, Subj)), [VarNameO-Subj]):-isSomeFn(SomeFn), getKeyVariable(Var, VarNameO), !.
dcgRedress([SomeFn|Rest], dcgReverse([SomeFn|Rest]), []):-isSomeFn(SomeFn), !.
dcgRedress(['PhraseCycLFn', Var, Rest], dcgAnd(DCG, theVar(VarNameO, Subj)), [VarNameO-Subj|Vars]):-getKeyVariable(Var, VarNameO), dcgRedress(Rest, DCG, Vars), !.
isLexicalWord(THEWORD):-not(atom(THEWORD)), !, fail.
isLexicalWord([]):-!, fail.
isLexicalWord(THEWORD):-atom_length(THEWORD, N), N<3, !, fail.
isLexicalWord(THEWORD):-atom_concat(_, '-TheWord', THEWORD), !.
isLexicalWord(THEWORD):-atom_concat(_, '-MWS', THEWORD).
isLexicalWord(THEWORD):-atom_concat(_, '-MWW', THEWORD).
isLexicalWord(THEWORD):-cycQueryIsaCache(THEWORD, 'LexicalWord').
dcgRedress([THEWORD, POS], theWord(THEWORD, POS), []):-isLexicalWord(THEWORD), !.
dcgRedress(['svar', P, OS], DCG, Vars):-dcgRedress('svar'(P, OS), DCG, Vars), !.
dcgRedress([THEWORD|POS], dcgReverse([THEWORD|POS]), []):-isLowercaseAtom(THEWORD), noteFmt('dcgReverse: ~q.~n', [[THEWORD|POS]]), list_dcgRedressStart.
isLowercaseAtom(THEWORD):-not(atom(THEWORD)), !, fail.
isLowercaseAtom([]):-!, fail.
isLowercaseAtom(THEWORD):-atom_codes(THEWORD, [C|_]), !, char_type(C, lower).
dcgRedress(DCG, Out, Vars):-notrace(once(cyc:decyclify(DCG, UDCG))), (DCG\== UDCG), !, throwOnFailure(dcgRedress(UDCG, Out, Vars)), !.
dcgRedress([TerseParaphraseFn, Phrase], dcgAnd(DCG, dcgNote(TerseParaphraseFn)), Vars):-
cmember(TerseParaphraseFn, ['TerseParaphraseFn', 'PreciseParaphraseFn']),
dcgRedress(Phrase, DCG, Vars), !.
dcgRedress([D|CG], dcgDressed(DCG), Vars):-compound(D), throwOnFailure((dcgRedressL([D|CG], RList, Vars), juntifyList(dcgSeq, RList, DCG))), !.
dcgRedress([D|CG], dcgDressedString(DCG), Vars):-atom(D), atom_concat('"', _, D), throwOnFailure((dcgRedressL([D|CG], RList, Vars), juntifyList(dcgSeq, RList, DCG))), !.
isNLFunctionNonExpandedArgs('NDecimalPlaceParaphraseFn').
dcgRedress([REDRESS, KW|ARGS], dcgNonExpandedVar(REDRESS, VarNameO, ARGS, Subj), [VarNameO-Subj]):-isNLFunctionNonExpandedArgs(REDRESS), getKeyVariable(KW, VarNameO), !.
dcgRedress([REDRESS|ARGS], dcgNonExpanded(REDRESS, ARGS), []):-isNLFunctionNonExpandedArgs(REDRESS), !.
isNLFunctionNonExpanded(A):-not(atom(A)), !, fail.
isNLFunctionNonExpanded([]):-!, fail.
isNLFunctionNonExpanded(NP, 'NounPhrase'):-holdsWithQuery(resultIsa, NP, 'NounPhrase'), !.
isNLFunctionNonExpanded('NPIsNP-NLSentenceFn', 'NLSentence'):-!.
isNLFunctionNonExpanded('NPIsXP-NLSentenceFn', 'NLSentence'):-!.
isNLFunctionNonExpanded(NP, RealType):-holdsWithQuery(resultIsa, NP, 'NLPhrase'), catch(cycQuery(and(resultIsa(NP, RealType), genls(RealType, 'NLPhrase'))), _, RealType='NLPhrase'), !,
noteFmt('nl: ~q.~n', [isNLFunctionNonExpanded(NP, RealType)]), !, list_dcgRedressStart.
dcgRedress([REDRESS|ARGS], dcgNonExpandedFrom(RI, REDRESS, DCG), Vars):- nonvar(REDRESS), isNLFunctionNonExpanded(REDRESS, RI), !,
% noteFmt('isNLFunctionNonExpanded: ~q.~n', [[REDRESS|ARGS]]), !, list_dcgRedressStart,
% trace,
dcgRedressL(ARGS, DCG, Vars), !.
%use expansion
dcgRedress([REDRESS|ARGS], Out, Vars):-fail,
isNLFunction(REDRESS),
holdsWithQuery(expansion, REDRESS, NEW),
cycUseExpansion([REDRESS|ARGS], NEW2),
dcgRedress(NEW2, Out, Vars), !,
noteFmt('~q -> ~q -> ~q ~n', [[REDRESS|ARGS], NEW2, Out]),
list_dcgRedressStart.
cycUseExpansion([REDRESS|ARGS], NEW2):-holdsWithQuery(expansion, REDRESS, NEW),
V = varHolder(NEW),
ignore((
nth0(N, [REDRESS|ARGS], ARG), N>0,
arg(1, V, Value),
atom_concat(':ARG', N, ARGNAME),
subst(Value, ARGNAME, ARG, NewValue),
nb_setarg(1, V, NewValue),
fail)),
arg(1, V, NEW2), !.
/*
%use expansion
dcgRedress([REDRESS, ARG1], Out, Vars):-isNLFunction(REDRESS), holdsWithQuery(expansion, REDRESS, NEW),
substEach(NEW, [':ARG1'-ARG1], NEW2), dcgRedress(NEW2, Out, Vars), !, list_dcgRedressStart.
dcgRedress([REDRESS, ARG1, ARG2], Out, Vars):- isNLFunction(REDRESS), holdsWithQuery(expansion, REDRESS, NEW),
substEach(NEW, [':ARG1'-ARG1, ':ARG2'-ARG2], NEW2), dcgRedress(NEW2, Out, Vars), !, list_dcgRedressStart.
dcgRedress([REDRESS, ARG1, ARG2, ARG3], Out, Vars):- isNLFunction(REDRESS), holdsWithQuery(expansion, REDRESS, NEW),
substEach(NEW, [':ARG1'-ARG1, ':ARG2'-ARG2, ':ARG3'-ARG3], NEW2), dcgRedress(NEW2, Out, Vars), !, list_dcgRedressStart.
dcgRedress([REDRESS, ARG1, ARG2, ARG3, ARG4], Out, Vars):- isNLFunction(REDRESS), holdsWithQuery(expansion, REDRESS, NEW),
substEach(NEW, [':ARG1'-ARG1, ':ARG2'-ARG2, ':ARG3'-ARG3, ':ARG4'-ARG4], NEW2), dcgRedress(NEW2, Out, Vars), !, list_dcgRedressStart.
dcgRedress([REDRESS, ARG1, ARG2, ARG3, ARG4, ARG5], Out, Vars):- isNLFunction(REDRESS), holdsWithQuery(expansion, REDRESS, NEW),
substEach(NEW, [':ARG1'-ARG1, ':ARG2'-ARG2, ':ARG3'-ARG3, ':ARG4'-ARG4, ':ARG5'-ARG5], NEW2), dcgRedress(NEW2, Out, Vars), !, list_dcgRedressStart.
*/
dcgRedress([REDRESS|ARGS], DCG, Vars):-isNLFunction(REDRESS),
noteFmt('isNLFunction: ~q.~n', [[REDRESS|ARGS]]), !, list_dcgRedressStart,
%trace,
dcgRedressL(ARGS, DCG, Vars), !.
%TODO comment out unless for file testing
dcgRedress([D|CG], dcgSeqReinterp([D|CG]), []):-noteFmt('dcgSeqReinterp: ~q.~n', [[D|CG]]), list_dcgRedressStart, !.
dcgRedress([D|CG], dcgSeqReinterp(DCG), Vars):-noteFmt('dcgSeqReinterp: ~q.~n', [[D|CG]]), list_dcgRedressStart,
throwOnFailure((dcgRedressL([D|CG], RList, Vars), juntifyList(dcgSeq, RList, DCG))), !.
dcgRedress('\\', dcgNone, []):-!.
dcgRedress(THEWORD, theWord(THEWORD), []):-isLexicalWord(THEWORD), !.
dcgRedress(VarName, dcgTemplate('AnyTemplate', VarNameO, Subj), [VarNameO-Subj]):-getKeyVariable(VarName, VarNameO), !.
dcgRedress(DCG, dcgReinterp(DCG), []):-noteFmt('dcgReinterp: ~q.~n', [DCG]), !, list_dcgRedressStart.
%holdsWithQuery(genTemplate, geographicalSubRegions, ['ConcatenatePhrasesFn', ['TermParaphraseFn-DO', svar(A, ':ARG2')], ['BestHeadVerbForInitialSubjectFn', 'Be-TheWord'], ['BestNLPhraseOfStringFn', string([a])], ['BestNLPhraseOfStringFn', string([geographical])], ['BestNLPhraseOfStringFn', string([subregion])], ['BestPPFn', 'Of-TheWord', ['TermParaphraseFn-DO', svar(B, ':ARG1')]]]).
%templateMarkerRepresentation(TemplateMarker, Char):-assertion(templateMarkerRepresentation, TemplateMarker, [(Char)]).
templateMarkerRepresentation('TemplateHyphenMarker', "-").
templateMarkerRepresentation('TemplateOpenBracketMarker', "[").
templateMarkerRepresentation('TemplateCloseBracketMarker', "]").
templateMarkerRepresentation('TemplateCloseParenMarker', "]").
templateMarkerRepresentation('TemplateDoubleQuoteMarker', "'").
templateMarkerRepresentation('TemplateSingleQuoteMarker', "'").
templateMarkerRepresentation('TemplateExclamationMarkMarker', "!").
templateMarkerRepresentation('TemplateQuestionMarkMarker', "?").
templateMarkerRepresentation('TemplateCommaMarker', ", ").
templateMarkerRepresentation('TemplateSemiColonMarker', ";").
templateMarkerRepresentation('TemplatePeriodMarker', ".").
templateMarkerRepresentation('TemplateColonMarker', ":").
toText([], []):-!.
toText(S, T):-cmember([txt|T], S), !.
toText([S|SS], TTT):-toText(S, T), toText(SS, TT), flatten([T|TT], TTT).
% =======================================================
% DCG Helpers/Operators (and some Terminals)
% =======================================================
%memberData(M, [W|Ws]):-textCached([W|Ws], M).
%memberData(M, [W|Ws]):-textCached([_, W|Ws], M), !.
%memberData(M, [W|Ws]):-textCached([W|_], M), !.
%memberData(M, W):-true, concat_atom(WList, '_', W), !, memberData(M, WList).
% Text
theText(_, [], _):- !, fail.
theText([S]) --> {!}, theGText(S).
theText([S|Text]) --> {nonvar(Text)}, [Data], {cmember([txt|[S|Text]], Data), !}.
theText([S|Text]) --> {nonvar(Text), !}, [Data], {cmember([txt, S], Data)}, theText(Text).
theText(S) --> {atom(S), atom_concat('"', Right, S), atom_concat(New, '"', Right), !}, theText(New).
theText(S) --> {atom(S), concat_atom([W1, W2|List], ' ', S), !}, theText([W1, W2|List]).
theText(S) --> theGText(S).
% Looser text test?
theGText(_, [], _):- !, fail.
theGText(S) --> {!}, [Data], {member([txt, S], Data)}.
theTerm(Term) --> theText([S|TEXT]), {textCached([S|TEXT], [denotation, _Pos, Term|_])}.
% bposToPos/2 is from [cyc_pos].
%thePOS(Pos) --> [Data], {once((memberchk([tag, _|POSs], Data), cmember(CPos, POSs), (Pos=CPos;bposToPos(CPos, Pos))))}.
thePOS(Pos) --> [Data], {notrace(isTag(Data, Pos))/* , ! */}.
thePOS('NLSentence') --> dcgZeroOrMore(dcgAny).
thePOS(Word, Pos) --> dcgAnd(thePOS(Pos), theWord(Word)).
theWord(_, [], _):- !, fail.
theWord(Word) --> theText([S|Text]), {once(textCached([S|Text], [lex, Word|_])), !}.
theWord('WordFn'(string([S|Text]))) --> theText([S|Text]), {!}.
%theWord(Word) --> theText([A]), {once(memberData([lex, Word|_], [A, B]))}, theText([B]).
theWord(_, _, [], _):- !, fail.
theWord(Word, Pos) --> {var(Word), !}, dcgAnd(thePOS(Pos), theWord(Word)).
theWord(Word, Pos) --> dcgAnd(theWord(Word), thePOS(Pos)).
theForm(PosForm)--> theText([S|Text]), {(textCached([S|Text], [lex, Word, PosForm|_]))}.
dcgPosVar(Pos, VarName, Subj)-->dcgAnd(thePOS(Pos), theVar(VarName, Subj)).
theName(Var, S, _) :-getText(S, Text), suggestVar(Text, Var), !.
theTense(Time) --> theForm(PosForm), {once(timeLookup(PosForm, Time))}.
thePerson(Pers) --> theForm(PosForm), {once(personLookup(PosForm, Pers))}.
theCount(Num) --> theForm(PosForm), {once(countLookup(PosForm, Num))}.
theAgreement(Pers, Num) --> theForm(When), {personLookup(When, Pers), countLookup(When, Num)}.
timeLookup(Atom, 'Now'):-atom(Atom), atom_concat(_, 'Present', Atom).
timeLookup(Atom, 'Past'):-atom(Atom), atom_concat(_, 'Past', Atom).
timeLookup(Atom, 'Future'):-atom(Atom), atom_concat(_, 'Future', Atom).
timeLookup(Atom, 'Now'):-atom(Atom), atom_concat('present', _, Atom).
timeLookup(Atom, 'Past'):-atom(Atom), atom_concat('past', _, Atom).
timeLookup(Atom, 'Future'):-atom(Atom), atom_concat('future', _, Atom).
countLookup(Atom, 'Plural'):-atom(Atom), atom_concat('plural', _, Atom).
countLookup(Atom, 'Plural'):-atom(Atom), atom_concat(_, 'Plural', Atom).
countLookup(Atom, 'Plural'):-atom(Atom), concat_atom([_, 'nonSing', _], Atom).
countLookup(Atom, 'Singular'):-atom(Atom), atom_concat('singular', _, Atom).
countLookup(Atom, 'Singular'):-atom(Atom), atom_concat(_, 'Singular', Atom).
countLookup(Atom, 'Singular'):-atom(Atom), concat_atom([_, 'Sg', _], Atom).
personLookup(Atom, 'First'):-atom(Atom), atom_concat('first', _, Atom).
personLookup(Atom, 'Second'):-atom(Atom), atom_concat('second', _, Atom).
personLookup(Atom, 'Third'):-atom(Atom), atom_concat('third', _, Atom).
theFrame(Event, FrameType, Pos, Template) --> theWord(Word), {getFrame(Word, Event, FrameType, Pos, Template), once(suggestVar(SText, Event))}.
%textCached('Lead-TheWord', [frame, 'Lead-TheWord', 'Verb', 'TransitiveNPFrame', and(isa(':ACTION', 'GuidingAMovingObject'), directingAgent(':ACTION', ':SUBJECT'), primaryObjectMoving(':ACTION', ':OBJECT')), verbSemTrans]).
% getFrame(Word, Event, 'ParticleCompFrameFn'('IntransitiveParticleFrameType', Prep), 'Verb', Template).
getFrame(Word, Event, FrameType, Pos, Template):-ground(FrameType), !, findall(CycL, (textCached(_, [frame, Word, Pos, FrameType, CycL, Pred])), Some), Some=[Lest|One], joinCols(or, [Lest|One], Template).
getFrame(Word, Event, FrameType, Pos, CycL):-textCached(_, [frame, Word, Pos, FrameType, CycL, Pred]).
getFrame(Word, Event, FrameType, Pos, CycL):- cycQuery(wordSemTrans(Word, Num, FrameType, CycL, Pos, Pred, Precons)).
templateConstaint('True', Template, Template):-!.
templateConstaint(Constraints, Template, implies(Constraints, Template)).
framePredForPos(Pos, Pred):-holdsWithQuery(semTransPredForPOS, Pos, Pred).
%framePredForPos('Preposition', 'prepReln-Action').
%framePredForPos('Preposition', 'prepReln-Object').
framePredForPos('Adjective', 'adjSemTrans-Restricted').
frameAdd:-cycQuery('adjSemTrans-Restricted'(WORD, NUM, FRAME, COL, CYCL), '#$EverythingPSC'), cycAssert(wordSemTrans(WORD, 'Adjective', NUM, FRAME, implies(isa(':NOUN', COL), CYCL), 'adjSemTrans-Restricted', _PreRequ), '#$EnglishMt'), fail.
frameAdd:-cycQuery('nounPrep'(WORD, PREP, CYCL), '#$EverythingPSC'), cycAssert(wordSemTrans(WORD, _Num, 'PPCompFrameFn'('TransitivePPFrameType', PREP), CYCL, 'Noun', 'nounPrep', _PreRequ), '#$EnglishMt'), fail.
%frameAdd:-cycQuery('prepReln-Action'(ACTION, OBJECT, WORD, CYCL), '#$EverythingPSC'), cycAssert(wordSemTrans(WORD, _Num, 'Post-VerbPhraseModifyingFrame', implies(and(isa(':ACTION', ACTION), isa(':OBLIQUE-OBJECT', OBJECT)), CYCL), 'Preposition', 'prepReln-Action', _PreRequ), '#$EnglishMt'), fail.
%frameAdd:-cycQuery('prepReln-Object'(NOUN, OBJECT, WORD, CYCL), '#$EverythingPSC'), cycAssert(wordSemTrans(WORD, _Num, 'Post-NounPhraseModifyingFrame', implies(and(isa(':NOUN', NOUN), isa(':OBLIQUE-OBJECT', OBJECT)), CYCL), 'Preposition', 'prepReln-Object', _PreRequ), '#$EnglishMt'), fail.
frameAdd(WORDS):-cycQuery('compoundSemTrans'(WORDS, WLIST, POS, FRAME, CYCL), '#$EverythingPSC'),
stringToWords(WLIST, WORDS).
stringToWords([], []).
stringToWords(TheList, Words):-functor(TheList, 'TheList', _), TheList=..[_|List], !, stringToWords(List, Words).
stringToWords(string(S), Words):-!, stringToWords(S, Words).
stringToWords(['TheList'|List], Words):-!, stringToWords(List, Words).
stringToWords([S|Tring], [W|Words]):-stringToWord(S, W), stringToWords(Tring, Words).
stringToWord([S], W):-!, textCached([S], [lex, W|_]).
stringToWord(S, W):-textCached([S], [lex, W|_]).
suggestVar(Subj, Subj):-var(Subj), !.
suggestVar(Subj, Subj2):-var(Subj), !.
suggestVar([W|ORDS], Subj):-!, ignore(notrace(once((nonvar(ORDS), concat_atom(['?'|[W|ORDS]], '', Suj), gensym(Suj, SubjSl), cyc:toUppercase(SubjSl, SubjS), ignore(SubjS=Subj))))), !.
suggestVar([], Subj):-!.%suggestVar([A], Subj), !.
suggestVar(A, Subj):-suggestVar([A], Subj), !.
suggestVarI([W|ORDS], Subj):-!, concat_atom(['?'|[W|ORDS]], '', Suj), cyc:toUppercase(Suj, SubjS), ignore(SubjS=Subj), !.
suggestVarI(A, Subj):-suggestVarI([A], Subj).
theIsa(Subj, COLS, ColType) --> theOneOfFn(Subj, COLS, ColType).
theOneOfFn(Subj, COLS, ColType)-->theWord(Word), {suggestVar(SText, Subj),
meetsRequirement(Word, ColType, COLSS), joinCols('OneOfFn', COLSS, COLS)}.
meetsRequirement(Word, ColType, COLSS):-
notrace(findall(COL, (textCached(Word, [denotation, _Pos, COL|DPROPS]), anyIsa([COL|DPROPS], ColType)), COLSS)), !, leastOne(COLSS).
leastOne([CO|LSS]).
anyIsa([COL|DPROPS], ColType):-member(One, [COL|DPROPS]), cycQuery(isa(One, ColType)), !.
%e2c_sem("the singer sang a song").
joinCols(JOINER, [CO|LS1], COLS):-list_to_set([CO|LS1], COLS1S), ([COLS]=COLS1S -> true; COLS=nart([JOINER|COLS1S])), !.
%constraintsOnIsa([_, _, [EQ|ColTypes]|_], EQ, nart(['CollectionIntersectionFn'|ColTypes])).
%constraintsOnIsa([_, _, [EQ]|_], EQ, 'Thing').
:-flag(dcg_template_depth, _, 0).
:-dynamic(current_dcg_template/2).
% current_dcg_template(?Template, ?Depth)
textMathesTemplate(T, TempType):-not(atom(TempType)), !, fail.
textMathesTemplate(T, TempType):- cmember(T, ['X', 'Y', 'Z']).
textMathesTemplate(Txt, TempType):- atom(Txt), concat_atom([_|_], Txt, TempType).
disable_dcgTemplate(TempType, VarName, cycForTemplate(VarName, TempType, TempType1), [TempTypeData|E], E):-
getText(TempTypeData, [TempType1]), textMathesTemplate(TempType1, TempType), !.
dcgTemplate(TempType, VarName, CycL, S, E):- TempType == 'AnyTemplate', !, dcgTemplate('NPTemplate', VarName, CycL, S, E).
dcgTemplate(TempType, VarName, CycL, S, E):-
(current_dcg_template(TempType, Prev)->(fail);true),
flag(dcg_template_depth, D, D+1),
asserta(current_dcg_template(TempType, D)),
(D<40 -> true ; fail),
%startsTemplateType(S, TempType),
appliedTemplate(TempType, _Pred, DCG, CycL),
throwOnFailure(callable(DCG)),
phrase(DCG, S, E),
flag(dcg_template_depth, DN, DN-1),
retractall(current_dcg_template(TempType, D)).
dcgNote(X)--> dcgConsumeData(True), {noteFmt('dcgNote(~q) for ~q )', [X, True]), !}.
dcgTemplateKW(KWs, VarName, Subj)-->{cmember(TempType, KWs)}, dcgTemplate(TempType, VarName, Subj).
dcgDressedString(X)-->dcgDressed(X).
dcgDressed(X)-->{throwOnFailure(nonvar(X)->callable(X);true)}, X.
startsTemplateType([A|B], VPTemplate, Type):-cmember([lex, _|POSVerb], A), !, cmember(Verb, POSVerb), holdsWithQuery(posForTemplateCategory, Verb, VPTemplate).
startsTemplateType([A|B], VPTemplate, Type).
dcgReinterp(Term) --> theTerm(Term).
theTermStrings(Term) --> theWord(Term).
theTermStrings(Term) --> theTerm(Term).
dcgOptionalOne([])-->[].
dcgOptionalOne([X|_])-->dcgDressed(X), (!).
dcgOptionalOne([_|Xs])-->dcgOptionalOne(Xs).
dcgStartsWith(TheType, SMORE, SMORE) :- phrase(TheType, SMORE, _).
dcgStartsWith1(TheType, [S|MORE], [S|MORE]) :- phrase(TheType, [S], []).
dcgAndRest(TheType, TODO, [S|MORE], []) :- phrase(TheType, [S], []), phrase(TheType, [S|MORE], []).
dcgConsumeRest(_, []).
dcgPreTest(DCG, SE, SE):-phrase(DCG, SE, []).
dcgContainsPreTest(DCG)-->dcgPreTest((dcgMapOne(DCG), dcgConsumeRest)).
% same dcgNoConsumeStarts(DCG, SE, SE):-dcgNoConsume((DCG, dcgConsumeRest), SE, SE).
dcgNoConsumeStarts(DCG, SE, SE):-phrase(DCG, SE, _).
:-dynamic(posOkForPhraseType(DefiniteNounPPFn, Pos)).
dcgPhraseType(DefiniteNounPPFn, DCG)--> dcgAnd((dcgStartsWith(thePOS(Pos)), {posOkForPhraseType(DefiniteNounPPFn, Pos)}), dcgDressed(X)).
dcgConstraintBindings(DCG, Constr) --> dcgDressed(DCG), {todo(cycQuery(Constr))}.
dcgConstraint(DCG, Constr) --> dcgDressed(DCG), {todo(cycQuery(Constr))}.
dcgCycL(DCG, Constr) --> {todo(getGenerationTemplateFor(dcgCycL(DCG, Constr, Template))), fail}, Template.
dcgMaybeQuoted(X)-->dcgDressed(X).
dcgConjWithWord(Num, [Word, ConjList]) --> dcgSeq(Num, ConjList).
dcgRepeatForSubsequentArgsFn(Num, Each)--> dcgDressed(Each).
dcgNoSpaces(X)-->dcgDressed(X).
dcgReverse(Rev) --> {todo(getGenerationTemplateFor(dcgReverse(Rev, Template))), fail}, Template.
dcgSeqReinterp(Rev) --> {todo(getGenerationTemplateFor(dcgReverse(Rev, Template))), fail}, Template.
dcgOptionalSome(X)-->dcgOptionalCount(X, _N).
dcgOptionalCount([], 0)-->[], {!}.
dcgOptionalCount([X|Xs], N)-->dcgDressed(X), {!}, dcgOptionalCount(Xs, N1), {N is N1 + 1}.
dcgOptionalCount([_X|Xs], N)-->dcgOptionalCount(Xs, N).
dcgRequireSome(_Num, X)-->dcgOptionalCount(X, N), {!, N>0}.
% Num + List of Items
dcgSeq(Num, List, B, E):-number(Num),
%is_list(List),
!, dcgSeq_phrase(List, B, E).
% Item1 + Item2
dcgSeq(X, Y, [S0, S1|SS], E):-phrase((X, Y), [S0, S1|SS], E).
dcgSeq(X, Y, Z, [S0, S1|SS], E):-phrase((X, Y, Z), [S0, S1|SS], E).
dcgSeq_phrase([], B, B) :- !.
dcgSeq_phrase([Dcg|List], B, E) :- catch(phrase(Dcg, B, M), E, (writeq(E+phrase(Dcg, B, M)), nl, fail)), dcgSeq_phrase(List, M, E).
dcgBoth(DCG1, DCG2, S, R) :- append(L, R, S), phrase(DCG1, L, []), once(phrase(DCG2, L, [])).
dcgAnd(DCG1, DCG2, DCG3, DCG4, S, E) :- phrase(DCG1, S, E), phrase(DCG2, S, E), phrase(DCG3, S, E), phrase(DCG4, S, E).
dcgAnd(DCG1, DCG2, DCG3, S, E) :- phrase(DCG1, S, E), phrase(DCG2, S, E), phrase(DCG3, S, E).
dcgAnd(DCG1, DCG2, [S|TART], E) :- phrase(DCG1, [S|TART], E), phrase(DCG2, [S|TART], E).
dcgOr(DCG1, DCG2, DCG3, DCG4, DCG5, S, E) :- phrase(DCG1, S, E);phrase(DCG2, S, E);phrase(DCG3, S, E);phrase(DCG4, S, E);phrase(DCG5, S, E).
dcgOr(DCG1, DCG2, DCG3, DCG4, S, E) :- phrase(DCG1, S, E);phrase(DCG2, S, E);phrase(DCG3, S, E);phrase(DCG4, S, E).
dcgOr(DCG1, DCG2, DCG3, S, E) :- phrase(DCG1, S, E);phrase(DCG2, S, E);phrase(DCG3, S, E).
dcgOr(Num, DCG2, S, E) :- number(Num), !, member(DCG, DCG2), phrase(DCG, S, E).
dcgOr(DCG1, DCG2, S, E) :- phrase(DCG1, S, E);phrase(DCG2, S, E).
dcgOr([D|CG1], S, E) :- member(One, [D|CG1]), phrase(One, S, E).
dcgNot(DCG2, S, E) :- not(phrase(DCG2, S, E)).
dcgIgnore(DCG2, S, E) :- ignore(phrase(DCG2, S, E)).
dcgOnce(DCG2, S, E) :- once(phrase(DCG2, S, E)).
dcgWhile(True, Frag)-->dcgAnd(dcgOneOrMore(True), Frag).
dcgOneOrMore(True) --> True, dcgZeroOrMore(True), {!}.
dcgZeroOrMore(True) --> True, {!}, dcgZeroOrMore(True), {!}.
dcgZeroOrMore(True) --> [].
dcgMapCar(Var, DCG, [Var|List])-->{copy_term(Var+DCG, Var2+DCG2)}, DCG, {!}, dcgMapCar(Var2, DCG2, List).
dcgMapCar(Var, DCG, [])-->[].
dcgMapSome(Var, DCG, [Var|List])-->{copy_term(Var+DCG, Var2+DCG2)}, DCG, {!}, dcgMapSome(Var2, DCG2, List).
dcgMapSome(Var, DCG, List)--> [_], {!}, dcgMapSome(Var, DCG, List).
dcgMapSome(Var, DCG, [])-->[].
dcgMapOne(Var, DCG)--> DCG, {!}.
dcgMapOne(Var, DCG)--> [_], dcgMapOne(Var, DCG).
dcgConsumeData([]) --> [].
dcgConsumeData([Data|More]) --> [Data], {!}, dcgConsumeData(More), {!}.
dcgLeftOf(Mid, [Left|T], S, [MidT|RightT]):-append([Left|T], [MidT|RightT], S), phrase(Mid, MidT), phrase([Left|T], LeftT).
dcgMid(Mid, Left, Right) --> dcgLeftOf(Mid, Left), Right.
scanDcgUntil(_, _, [], __):-!, fail.
scanDcgUntil(DCG, [], [Found|Rest], [Found|Rest]):-phrase(DCG, [Found], []), !.
scanDcgUntil(DCG, [Skipped|Before], [Skipped|More], [Found|Rest]):-scanDcgUntil(DCG, Before, More, [Found|Rest]).
dcgNone --> [].
dcgAny --> [_].
% Matches the rightmost DCG item
dcgLast(DCG, S, Left):-append(Left, [Last], S), phrase(DCG, [Last]).
dcgIfThenElse(DCG, True, False, S, E) :- phrase(DCG, S, M) -> phrase(True, M, E) ; phrase(False, S, E).
dcgIfThenOr(DCG, True, False, S, E) :- (phrase(DCG, S, M) , phrase(True, M, E)) ; phrase(False, S, E).
dcgOptional(A)-->dcgOnce(dcgOr(A, dcgNone)).
%throwOnFailure(X):-once(X;(trace, X)).
debugOnError(X):-catch(X, E, (writeq(E), trace, X)).
dcgNonExpandedFrom(Pos, GenValueParaphraseFn, ConjList) --> dcgSeq_phrase(ConjList).
dcgNonExpandedVar(NDecimalPlaceParaphraseFn, VARG1 , [Num], Var) -->
dcgAnd(theVar(VARG1, Var), dcgNote(dcgNonExpandedVar(NDecimalPlaceParaphraseFn, VARG1 , [Num], Var))).
capitalized([W|Text]) --> theText([W|Text]), {atom_codes(W, [C|Odes]), is_upper(C)}.
substAll(B, [], R, B):-!.
substAll(B, [F|L], R, A):-subst(B, F, R, M), substAll(M, L, R, A).
substEach(B, [], B):-!.
substEach(B, [F-R|L], A):-subst(B, F, R, M), substEach(M, L, A).
% =======================================================
% utterance_sem(Event, CycL, [every, man, that, paints, likes, monet], [])
% =======================================================
%utterance_sem(Event, CycL) -->utterance_sem(Event, CycL1), {substEach(CycL1, [':POSSESSOR'-Pos], CycL), suggestVar('POSSESSOR', Pos)}.
englishCtx(Event, thereExists(Event, CycL)) --> utterance_sem(Event, CycL).
%utterance_sem(Event, 'NothingSaid') -->[].
utterance_sem(Event, CycL) -->['S'|Form], {!, throwOnFailure(phrase(utterance_sem(Event, CycL), Form))}.
utterance_sem(Event, template(TempType, CycL)) --> {cmember(TempType, ['STemplate'])}, dcgTemplate(TempType, Event, CycL).
utterance_sem(Event, template(TempType, CycL)) --> dcgTemplate(TempType, Event, CycL).
%utterance_sem(Event, CycL) --> noun_unit(Type, Event, Subj, holdsIn('Now', Subj), CycL).
%utterance_sem(Event, CycL, S, []) :- once((ground(S), toText(S, T))), cyclifyTest(string(T), CycL).
utterance_sem(Event, forAll(Subj, forAll(Obj, implies(isa(Subj, SType), isa(Obj, SObj))))) --> universal_word(Form), dcgAnd(theIsa(Subj, SType, 'Collection'), theForm(Form)), thePOS('BeAux'), theIsa(Obj, SObj, 'Collection').
utterance_sem(Event, CycL) --> declaritive_sentence(Subj, Event, Obj, CycL), nonQMarkPunct.
utterance_sem(Event, CycL) --> imparitive_sentence(Event, CycL), nonQMarkPunct.
utterance_sem(Event, 'CYC-QUERY'(CycL)) --> inquiry(Event, CycL).
%utterance_sem(Event, and(CycL1, CycL2)) -->utterance_sem(Event, CycL1), utterance_sem(Event, CycL2).
nonQMarkPunct --> dcgAnd(thePOS('Punctuation-SP'), dcgNot(theWord('QuestionMark-TheSymbol'))).
nonQMarkPunct --> [].
imparitive_sentence(Event, CycL) --> thePOS('Interjection-SpeechPart'), {!}, imparitive_sentence(Event, CycL).
imparitive_sentence(Event, utters('?SPEAKER', Word, Means)) --> dcgAnd(thePOS(Word, 'Interjection-SpeechPart'), dcgIgnore(theTerm(Means))).
imparitive_sentence(Event, CycL) --> theWord('Please-TheWord'), {!}, imparitive_sentence(Event, CycL).
imparitive_sentence(Event, CycL) --> verb_phrase(Time, Subj, Obj, Event, CycL), {suggestVarI('TargetAgent', Subj), suggestVar('ImparitiveEvent', Event)}.
chunkParseCycL(Event, Subj, Tagged, CycL9):-
sentenceChunker(Tagged, Chunks), nl,
parseCycLChunk(and(isa(Event, 'Situation'), situationConstituents(Event, Subj)), Chunks, Event, Subj, CycL9).
parseCycLChunk(_CycLIn, Chunks, _Event, Subj, _):-once(dumpList(Chunks)), nl, true, fail.
% tail closer
parseCycLChunk(CycLIn, [], Event, Subj, CycLIn):-!, suggestVar('SENTENCE', Event), suggestVar('SUBJECT', Subj).
parseCycLChunk(CycLIn, [seg(cc, _, _, _)|Const], Event, Subj, CycL) :-
parseCycLChunk(CycLIn, Const, Event, Subj, CycL).
parseCycLChunk(CycLIn, [seg(cs, _, _, _)|Const], Event, Subj, CycL) :-
parseCycLChunk(CycLIn, Const, Event, Subj, CycL).
parseCycLChunk(CycLIn, [seg(sym, _, [X], _)|Const], Event, Subj, CycL):- cmember(X, [('.'), ('!'), (', ')]), !,
parseCycLChunk(CycLIn, Const, Event, Subj, CycL).
parseCycLChunk(CycLIn, Const, Event, Subj, 'CYC-ASSERT'(CycL)) :- append(Const1, [seg(sym, _, [X], _)], Const), cmember(X, [('.'), ('!'), (', ')]), !,
parseCycLChunk(CycLIn, Const1, Event, Subj, CycL).
parseCycLChunk(CycLIn, Const, Event, Subj, 'CYC-QUERY'(CycL)) :- append(Const1, [seg(sym, _, [X], _)], Const), cmember(X, [('?')]), !,
parseCycLChunk(CycLIn, Const1, Event, Subj, CycL).
objTypeCompat(ObjType2, ObjType1):-var(ObjType2), var(ObjType1), !.
objTypeCompat(ObjType2, ObjType1):-(var(ObjType2);var(ObjType1)), !, fail.
objTypeCompat(ObjType1, ObjType1).
isConjoined(seg(in, _, [with], _), with).
isConjoined(seg(cc, _, [Conj], _), Conj).
% theObject and theObject -> theObject
parseCycLChunk(CycLIn, Const, Event, SubjThru, CycLO) :-
append(ConstL, [theObject(ObjType1, Subj1, W1), WITH, theObject(ObjType2, Subj2, W2)|ConstR], Const),
isConjoined(WITH, Conj), objTypeCompat(ObjType2, ObjType1), !,
append(W1, [Conj|W2], W),
append(ConstL, [theObject(ObjType1, Subj, W)|ConstR], NConst),
parseCycLChunk(and(memberOfList(Subj, 'TheList'(Subj1, Subj2)), CycLIn), NConst, Event, SubjThru, CycLO), !,
ignore(SubjThru=Subj),
suggestVar(W, Subj), !.
% Convert PN -> NPs
parseCycLChunk(CycLIn, Const, Event, SubjThru, CycLO) :-
append(ConstL, [seg(pn, T1, W1, D1)|ConstR], Const),
append(ConstL, [seg(np, T1, W1, D1)|ConstR], NConst),
parseCycLChunk(CycLIn, NConst, Event, SubjThru, CycLO).
% First NP -> theObject
%parseCycLChunk(CycLIn, [seg(np, T1, W1, D1)|ConstR], Event, Subj, CycL) :-
% phrase(noun_unit(T1, Event, Subj, CycLO, CycL), D1),
% parseCycLChunk(CycLIn, [theObject(ObjType, Subj, W1)|ConstR], Event, Subj, CycLO).
% NP + OF + NP
parseCycLChunk(CycLIn, Const, EventThru, SubjThru, CycLOut):-
append(ConstL, [seg(np, T1, W1, D1), seg(in, 'IN', [of], [PTAG]), seg(np, T2, W2, D2)|ConstR], Const),
append(W1, [of|W2], W), append(D1, [PTAG|D2], D),
append(ConstL, [seg(np, T2, W, D)|ConstR], NConst), %!,
parseCycLChunk(CycLIn, NConst, EventThru, SubjThru, CycLOut).
% NP + AT + NP
no_parseCycLChunk(CycLIn, Const, EventThru, SubjThru, CycLOut):-
append(ConstL, [seg(np, T1, W1, D1), seg(in, 'IN', [at], [PTAG]), seg(np, T2, W2, D2)|ConstR], Const),
append(W1, [at|W2], W), append(D1, [PTAG|D2], D),
append(ConstL, [seg(np, T2, W, D)|ConstR], NConst), %!,
parseCycLChunk(CycLIn, NConst, EventThru, SubjThru, CycLOut).
% NP -> theObject
parseCycLChunk(CycLIn, Const, Event, SubjThru, CycL) :-
append(ConstL, [seg(np, T1, W1, D1)|ConstR], Const),
asNounUnit(ObjType, T1, D1, W1, Event, Subj, CycLO, CycL),
append(ConstL, [theObject(ObjType, Subj, W1)|ConstR], NConst),
parseCycLChunk(CycLIn, NConst, Event, SubjThru, CycLO), suggestVar(W1, Subj).
% theObject + VP + theObject + IN + theObject -> theEvent
parseCycLChunk(CycLIn, Const, EventThru, SubjThru, CycLOut):-
append(ConstL, [theObject(ObjType1, Subj, SWords), seg(vp, Type, TXT, VTAG), theObject(ObjType2, Obj, OWords), seg(in, PType, PTXT, PTAG), theObject(ObjType3, Target, TWords)|ConstR], Const),
append(ConstL, [theObject('Action', Event, TXT), theObject(ObjType1, Subj, SWords)|ConstR], NConst),
phrase(verb_prep(Event, Subj, Obj, PTAG, Target, CycL), VTAG),
parseCycLChunk(and(CycL, CycLIn), NConst, EventThru, SubjThru, CycLOut), suggestVar(TXT, Event).
% theObject + VP + theObject + IN + theObject -> theEvent
parseCycLChunk(CycLIn, Const, EventThru, SubjThru, CycLOut):-
append(ConstL, [theObject(ObjType1, Subj, SWords), seg(vp, Type, TXT, VTAG), seg(in, PType, PTXT, PTAG), theObject(ObjType3, Target, TWords)|ConstR], Const),
append(ConstL, [theObject('Action', Event, TXT), theObject(ObjType1, Subj, SWords)|ConstR], NConst),
phrase(verb_prep(Event, Subj, Target, PTAG, Target, CycL), VTAG),
parseCycLChunk(and(CycL, CycLIn), NConst, EventThru, SubjThru, CycLOut), suggestVar(TXT, Event).
% theObject + VP + IN + theObject -> theEvent
parseCycLChunk(CycLIn, Const, EventThru, SubjThru, CycLOut):-
append(ConstL, [theObject(ObjType1, Subj, SWords), seg(vp, Type, TXT, VTAG), seg(in, PType, PTXT, PTAG), theObject(ObjType2, Target, TWords)|ConstR], Const),
append(ConstL, [theObject('Action', Event, TXT), theObject(ObjType1, Subj, SWords)|ConstR], NConst),
append(VTAG, PTAG, TAGGED),
phrase(verb2(Event, Subj, Target, CycL), TAGGED),
parseCycLChunk(and(CycL, CycLIn), NConst, EventThru, SubjThru, CycLOut), suggestVar(TXT, Event).
% theObject + VP + theObject -> theEvent
parseCycLChunk(CycLIn, Const, EventThru, SubjThru, CycLOut):-
append(ConstL, [theObject(ObjType1, Subj, SWords), seg(vp, Type, TXT, VTAG), theObject(ObjType2, Obj, OWords)|ConstR], Const),
append(ConstL, [theObject('Action', Event, TXT), theObject(ObjType1, Subj, SWords)|ConstR], NConst),
phrase(verb2(Event, Subj, Obj, CycL), VTAG),
parseCycLChunk(and(CycL, CycLIn), NConst, EventThru, SubjThru, CycLOut), suggestVar(TXT, Event).
% theObject + VP -> theEvent
parseCycLChunk(CycLIn, Const, EventThru, SubjThru, CycLOut):-
append(ConstL, [theObject(ObjType1, Subj, SWords), seg(vp, Type, TXT, VTAG)|ConstR], Const),
append(ConstL, [theObject('Action', Event, TXT), theObject(ObjType1, Subj, SWords)|ConstR], NConst),
phrase(verb1(Event, Subj, CycL), VTAG),
parseCycLChunk(and(CycL, CycLIn), NConst, EventThru, SubjThru, CycLOut), suggestVar(TXT, Event).
% Convert IN -> VP
parseCycLChunk(CycLIn, Const, Event, SubjThru, CycLO) :-
append(ConstL, [seg(in, T1, W1, D1)|ConstR], Const),
append(ConstL, [seg(vp, T1, W1, D1)|ConstR], NConst), !,
parseCycLChunk(CycLIn, NConst, Event, SubjThru, CycLO).
% Skipovers
parseCycLChunk(CycLIn, [theObject(Action, Var, Words)|Rest], EventThru, SubjThru, and('subEvents'(EventThru, Var), CycL)) :-
Action == 'Action', !, suggestVar(Var, Words),
parseCycLChunk(CycLIn, Rest, EventThru, SubjThru, CycL).
parseCycLChunk(CycLIn, [theObject(ObjType, Var, Words)|Rest], EventThru, SubjThru, and('doom:descriptionStrings'(Var, string(Words)), CycL)) :-!, suggestVar(Var, Words),
ignore(Var=SubjThru), parseCycLChunk(CycLIn, Rest, EventThru, SubjThru, CycL).
parseCycLChunk(CycLIn, [seg(PC, Type, Words, Tagged)|Rest], EventThru, SubjThru, and('doom:descriptionStrings'(Subj, string(Words), PC), CycL)) :- !,
parseCycLChunk(CycLIn, Rest, EventThru, SubjThru, CycL), suggestVar(Subj, Words).
parseCycLChunk(CycLIn, [Err|Rest], Event, Subj, and('doom:descriptionErrorStrings'(Subj, string(Words)), CycL)) :- true,
parseCycLChunk(CycLIn, Rest, Event, SubjNext, CycL).
verb1(Event, Subj, and(actors(Event, Subj), CycL))-->verb_unit(Type, Time, Subj, Obj, Target, Event, CycL).
verb2(Event, Subj, Obj, CycL)-->verb_unit(Type, Time, Subj, Obj, Target, Event, CycL).
skip(string(C))-->[X], {getText(X, C)}.
% =======================================================
% utterance_sem(Event, CycL, [every, man, that, paints, likes, monet], [])
% =======================================================
sent(Event, Subj, 'CYC-ASSERT'(CycL9)) -->dcgLast(theText([X])), {member(X, [('.'), ('!'), (', ')]), !}, sent(Event, Subj, CycL9).
sent(Event, Subj, CycL) -->(theText([X])), {member(X, [('.'), ('!'), (', ')]), !}, sent(Event, Subj, CycL).
sent(Event, Subj, CycL) -->dcgLast(theText([X])), {member(X, [('?')]), !}, sent(Event, Subj, CycL).
sent(Event, Subj, 'CYC-QUERY'(CycL9))-->thePOS('Modal'), !, sent(Event, Subj, CycL9).
sent(Event, Subj, verbSubjObj(Event, Subj, Obj, CycL9)) --> noun_unit(Type, Event, Subj, VerbIn, CycL9), vp(Event, Subj, Obj, VerbIn).
sent(Event, Subj, verbSubjObj(Event, '?TargetAgent', Obj, CycL9)) --> vp(Event, Subj, Obj, CycL9).
sent(Event, Subj, CycL9) --> noun_unit(Type, Event, Subj, the(Subj), CycL9).
sent(Event, Subj, and(isa(Event, 'Event'), CycL9)) --> rel_clause_sem(Event, Subj, CycL9).
%You could apply chineese room to human physical neurons.. but does that make us unintelligent?
joinNP(N1, no(noun), N1):-!.
joinNP('NounFn'(N1), 'NounFn'(N2), 'NounFn'(N1, N2)):-!.
joinNP(N1, N2, 'JoinFn'(N1, N2)).
/*
vp(Event, Subj, Obj1, and(CycL5, CycL9)) -->vp1(Event, Subj, Obj1, CycL5), conj(CC), vp1(Event, Subj, Obj2, CycL9).
vp(Event, Subj, Obj, CycL9) -->vp1(Event, Subj, Obj, CycL9).
compressed is :
*/
vp(Event, Subj, Obj, CycLO) --> vp1(Event, Subj, Obj, CycL5),
dcgIfThenElse((conj(CC), vp1(Event, Subj, Obj2, CycL9)), {CycLO=and(CycL5, CycL9)}, {CycLO=CycL5}).
/*
vp1(Event, Subj, Obj, and(hasAttribute(Event, AVP), CycL9)) --> verb_unit(Type, Time, Subj, Obj, Target, Event, CycL5), object_prep_phrase(Event, Obj, CycL5, CycL9), adv(AVP).
vp1(Event, Subj, Obj, CycL9) --> verb_unit(Type, Time, Subj, Obj, Target, Event, CycL5), object_prep_phrase(Event, Obj, CycL5, CycL9).
compressed is :
*/
vp1(Event, Subj, Obj, holdsIn(Time, CycL9))-->verb_phrase(Time, Subj, Obj, Event, CycL9).
vp1(Event, Subj, Obj, CycLO) --> verb_unit(Type, Time, Subj, Obj, Target, Event, CycL5), object_prep_phrase(Event, Obj, CycL5, CycL9),
dcgIfThenElse(adv(AVP), {CycLO=and(hasAttribute(Event, AVP), CycL9)}, {CycLO=CycL9}).
object_prep_phrase(Event, Obj, CycL0, CycL9) --> noun_unit(Type, Event, Obj, CycL0, CycL5),
thePrep(Event2, P), noun_unit(Type, Event2, Subj, thereExists(Event2, and(isa(Event2, 'Situation'), actorIn(Event2, Subj))), CycL9), {!}.
object_prep_phrase(Event, Obj, CycL0, CycL9) --> noun_unit(Type, Event, Obj, CycL0, CycL9).
object_prep_phrase(Event, Obj, CycL0, and(CycL0, CycL)) --> sent(Event, Obj, CycL).
object_prep_phrase(Event, Obj, CycL0, CycL0)-->[].
% :-ignore((predicate_property(aux(_, _, _), PP), writeq(PP), nl, fail)).
auxV(_, [], _):-!, fail.
auxV(AVP) --> thePOS(AVP, 'Modal').
auxV(AVP) --> thePOS(AVP, 'AuxVerb').
adv(_, [], _):-!, fail.
adv('Adverb2Fn'(AVP, AVP1))-->thePOS(AVP, 'Adverb'), conj(CC), thePOS(AVP1, 'Adverb'), {!}.
adv('AdverbFn'(AVP))-->thePOS(AVP, 'Adverb').
thePrep(_, _, [], _):-!, fail.
thePrep(Event2, P)-->conj(CC), {!}, thePrep(Event2, P).
thePrep(Event2, 'PrepAFn'(P, V))-->auxV(V), {!}, thePrep(Event2, P).
thePrep(Event2, 'PrepJoinFn'(P, P2))-->dcgBoth((thePOS(P, 'Preposition'), thePOS(P2, 'Preposition')), theName(Event2)).
thePrep(Event2, 'PrepositionFn'(P))-->dcgBoth((thePOS(P, 'Preposition')), theName(Event2)).
conj(_, [], _):-!, fail.
conj(CC)-->theWord('As-TheWord'), theWord('Well-TheWord'), theWord('As-TheWord').
conj(CC)-->conj1(_), conj1(_), conj1(CC).
conj(CC)-->conj1(_), conj1(CC).
conj(CC)-->conj1(CC).
conj1(CC)-->theText([(', ')]).
conj1(CC)-->thePOS(CC, 'CoordinatingConjunction').
declaritive_sentence(Subj, Event, Obj, and(CycL, HowDoes)) --> theFrame(Event, 'Pre-NounPhraseModifyingFrame', _, Template),
declaritive_sentence(Subj, Event, Obj, CycL), {substEach(Template, [':SUBJECT'-Subj, ':NOUN'-Subj, ':ACTION'-Event, ':OBJECT'-Obj], HowDoes)}.
declaritive_sentence(Subj, Event, Obj, CycL9) --> theWord('From-TheWord'), {!}, noun_unit(Type, Event, Target, and(CycL1, 'from-Underspecified'(Target, Obj)), CycL9), theText([(, )]),
declaritive_sentence(Subj, Event, Obj, CycL1).
declaritive_sentence(Subj, Event, Obj, CycL) --> noun_unit(Type, Event, Subj, CycL1, CycL), verb_phrase(Time, Subj, Obj, Event, CycL1).
%declaritive_sentence(Subj, Event, Obj, CycL) --> noun_unit(Type, Event, Subj, and(CycL1, CycL2), CycL),
%declaritive_sentence(Subj, Event, Obj, CycL) --> theWord('The-TheWord'), trans2_verb_unit(Type, Subj, Event, Obj, VProp), possible_prep, noun_unit(Type, Event, Obj, VProp, CycL1), theWord('Be-TheWord'), noun_unit(Type, Event, Subj, CycL1, CycL).
%declaritive_sentence(Subj, Event, Obj, CycL) --> noun_unit(Type, Event, Obj, VProp, CycL1), theWord('The-TheWord'), trans2_verb_unit(Type, Subj, Event, Obj, VProp), possible_prep, noun_unit(Type, Event, Obj, VProp, CycL1), theWord('Be-TheWord'), noun_unit(Type, Event, Subj, CycL1, CycL).
declaritive_sentence(Subj, Event, Obj, CycL) -->{!}, sent(Event, Subj, CycL).
possible_prep-->[of];[].
inquiry(Event, 'thereExists'(Actor, CycL)) --> wh_pronoun(Actor), verb_phrase(Time, Actor, Obj, Event, CycL), theText([?]), {suggestVar('Event', Event)}.
inquiry(Event, CycL) --> inv_sentence(Event, CycL), theText([?]).
%inquiry(CycL) --> declaritive_sentence(Subj, Event, Obj, CycL), theText([?]).
inv_sentence(Event, holdsIn(Time, CycL)) --> verbal_aux(Time), utterance_sem(Event, CycL).
verbal_aux(Time) --> aux_phrase(Time, Subj, Obj, Event, CycL).
%WHAdverb aux_phrase(Time, Subj, Obj, Event, CycL),
wh_pronoun('?Who') --> theWord('Who-TheWord').
wh_pronoun('?What') --> theWord('What-TheWord').
% =======================================================
% DCG Tester
% =======================================================
testPhrase(Dcg, English):-
sentenceTagger(English, Tagged), dumpList(Tagged),
phrase(Dcg, Tagged, Left),
nl, nl, writeq(left),
nl, dumpList(Left).
% =======================================================
% Rel Clauses
% see http://en.wikipedia.org/wiki/Relative_clause
% =======================================================
whomThatWhich(Word)-->dcgAnd(dcgOr([theTerm('Backreference-ClassB-NLAttr'), theWord('Who-TheWord'), thePOS('ExpletivePronoun'),
theWord('Whom-TheWord'), theWord('Which-TheWord'), theWord('Whose-TheWord'), theWord('That-TheWord')]), theWord(Word)), {!}.
% kill driving
notPresentParticiple --> dcgAnd(thePOS('Verb'), (theForm('presentParticiple'))), {!, fail}.
% drove
notPresentParticiple --> dcgAnd(thePOS('Verb'), dcgNot(theForm('presentParticiple'))).
% is driving
notPresentParticiple --> thePOS('BeAux'), presentParticiple.
% can drive
notPresentParticiple --> thePOS('Modal'), notPresentParticiple.
% the driver
notPresentParticiple --> thePOS('Determiner-Central'), thePOS('AgentiveNoun').
notPresentParticiple --> thePOS('regularAdverb'), notPresentParticiple.
% kill drove
presentParticiple --> dcgAnd(thePOS('Verb'), dcgNot(theForm('presentParticiple'))), {!, fail}.
% driving
presentParticiple --> dcgAnd(thePOS('Verb'), theForm('presentParticiple')).
% that ..
presentParticiple --> whomThatWhich(Word), {!, true}.
% that [ drove | is driving ]
presentParticiple --> whomThatWhich(Word), notPresentParticiple.
% quickly driving
presentParticiple --> thePOS('regularAdverb'), presentParticiple.
% from Nantucket
presentParticiple --> thePOS('Proposition').
% DCG circuit
relationl_clause_head(_, [], _):-!, fail.
% driving
% that drove
% that is driving
% that can drive
% who is driving
% whom drives
% the driver
% who is the driver
% that is from dover
relationl_clause_head --> presentParticiple.
% named Bilbo
% ... todo ...
% whose daughter is ill
% than whom I am smaller
% to whom I have written
% DCG circuit
rel_clause_sem(Event, Subj, SubjObjectCycL, [], _):-!, fail.
% of stuff
% on a shelf with a ball
rel_clause_sem(Event, Subj, SubjObjectCycL) -->
theFrame(Event, 'Post-NounPhraseModifyingFrame', _, Template),
noun_unit(Type, Event, Obj, HowDoes, SubjObjectCycL),
{substEach(Template, [':SUBJECT'-Subj, ':NOUN'-Subj, ':ACTION'-Event, ':OBJECT'-Obj, ':OBLIQUE-OBJECT'-Obj], HowDoes)}.
% that Verb Phrase
rel_clause_sem(Event, Subj, CycL9) --> theTerm('Backreference-ClassB-NLAttr'), verb_phrase(Time, Subj, Obj, Event, CycL9).
% who Verb Phrase
rel_clause_sem(Event, Subj, More) --> dcgAnd(thePOS('wps'), pronoun(Subj, CycL9, More)), verb_phrase(Time, Subj, Obj, Event, CycL9).
% named Benji
rel_clause_sem(Event, Subj, 'and'(IsaCycL, ProperNameCycL)) --> theWord('Name-TheWord'), proper_name(Subj, ProperNameCycL).
% on the shelf
%rel_clause_sem(Event, Subj, SubjIsaCycL, 'rpand'(SubjIsaCycL, preactors(Event, Obj))) --> prepositional_noun_phrase(Event, Subj, Obj, SubjIsaCycL, Prep).
% needs p2c("kissed it", (verb_phrase(X, Y, Z, A, B), dcgWordList(List))).
% needs p2c("driving southward", (verb_phrase(X, Y, Z, A, B), dcgWordList(List))).
% sitting on the shelf / kissed it
rel_clause_sem(Event, Subj, SubjIsaCycL, 'vpand'(SubjIsaCycL, VPCycL, timeOf(Event, Time))) -->dcgStartsWith(theForm('presentParticiple')),
verb_phrase(Time, Subj, Obj, Event, VPCycL).
% of Dover
%rel_clause_sem(Event, Subj, CycL9)-->theWord('Of-TheWord'), noun_unit(Type, Event2, Subj, thereExists(Event2, and(isa(Event2, 'Situation'), actorIn(Event2, Subj))), CycL9), {!}.
rel_clause_sem(Event, Subj, 'QueryFn'(That, CycL2))-->thePOS(That, 'WHAdverb'), {!}, sent(Event, Subj, CycL2), {!}.
%rel_clause_sem(Event, Subj, CycL0, whp(DE), V) -->thePOS(DET, 'WHPronoun'), {!}, verb_unit(Type, V).
%rel_clause_sem(Event, Subj, 'WhDeterminerFn'(Subj, Obj, CycL9))-->thePOS(That, 'Determiner'), vp1(Event, Subj, Obj, CycL9), {!}.
%rel_clause_sem(Event, Subj, and(isa(Event2, That), 'ThatFn'(That, Subj, Obj, CycL9)))-->thePrep(Event2, That), vp1(Event2, Subj, Obj, CycL9), {!}.
%verb_intransitive(Time, Subj, Obj, Event, 'and'('bodilyDoer'(Subj, Event), 'isa'(Event, actOf(paint)))) --> [paints].
%rel_clause_sem(Event, Subj, CycL0, 'and'(CycL0, HowDoes)) --> theWord('That-TheWord'), verb_phrase_premods(Time, Subj, Obj, Event, Does, HowDoes), verb_phrase(Time, Subj, Obj, Event, Does).
% =======================================================
% Nouns Phrases
% =======================================================
theRestText(Text) -->theText(Text1), theRestText1(Text2), {flatten([Text1, Text2], Text), !}.
theRestText1(Text) -->theText(Text1), theRestText1(Text2), {flatten([Text1, Text2], Text), !}.
theRestText1([]) -->[].
% =======================================================
% Nouns Units Each
% =======================================================
% p2c("$ 1", noun_unit(Type, Event, Subj, CycLIn, CycLOut)).
% p2c("my $ 1", noun_unit(Type, Event, Subj, CycLIn, CycLOut)).
% p2c("my car", noun_unit(Type, Event, Subj, CycLIn, CycLOut)).
% p2c("I", noun_unit(Type, Event, Subj, CycLIn, CycLOut)).
% p2c("me", noun_unit(Type, Event, Subj, CycLIn, CycLOut)).
% p2c("large number of birds", noun_unit(X, Y, Z, A, B)).
% p2c("United States of America", noun_unit(X, Y, Z, A, B)).
% p2c("United States of Americana", noun_unit(X, Y, Z, A, B)).
% p2c("the United States of America", noun_unit(X, Y, Z, A, B)).
%textCached([fond], [frame, adjSemTrans, 'PPCompFrameFn'('TransitivePPFrameType', 'Of-TheWord'), 'Adjective', feelsTowardsObject(':NOUN', ':OBLIQUE-OBJECT', 'Affection', positiveAmountOf)]).
%textCached([fond], [frame, adjSemTrans, 'PPCompFrameFn'('TransitivePPFrameType', 'Of-TheWord'), 'Adjective', feelsTowardsObject(':NOUN', ':OBLIQUE-OBJECT', 'Affection', positiveAmountOf)]).
%textCached([of], [frame, prepSemTrans, 'Post-NounPhraseModifyingFrame', 'Preposition', possessiveRelation(':OBJECT', ':NOUN')]).
%asNounUnit(ObjType, T1, D1, W1, Event, Subj, CycLO, CycL):-append([A|Djs], [Noun], D1),
% asNounQualifiers([A|Djs], Event, Subj, CycLQ),
% asNoun([Noun], Event, Subj, CycLN).
asNounUnit(ObjType, T1, D1, W1, Event, Subj, CycLO, CycL):-phrase(noun_unit(T1, Event, Subj, CycLO, CycL), D1), !.
asNounUnit(ObjType, T1, D1, W1, Event, Subj, CycLO, and(CycLO, 'doom:descriptionStrings'(Subj, string(W1)))):-!.
noun_unit(Adjective, Event, Subj, CycLIn, CycLO, [], _) :-!, fail.
% this prefers to cut noun units shorter than "offered" at least once "not presentParticiple" because we want relatinal clauses
noun_unit(Type, Event, Subj, CycLIn, CycLO, S, [Verb|Rest]) :-
scanDcgUntil(dcgAnd( thePOS('Verb'), dcgNot(theForm('presentParticiple'))), Before, S, [Verb|Rest]),
phrase(noun_unit(Type, Event, Subj, CycLIn, CycLO1), Before, []).
% p2c("at least three cars drove south", (noun_unit(X, Y, Z, A, B), dcgWordList(List))).
% p2c("at least three cars driving south", (noun_unit(X, Y, Z, A, B), dcgWordList(List))).
% p2c("the boy than whom I am smaller", (noun_unit(X, Y, Z, A, B), dcgWordList(List))).
% p2c("the boy whose daughter is ill", (noun_unit(X, Y, Z, A, B), dcgWordList(List))).
% p2c("the boy to whom I have written", (noun_unit(X, Y, Z, A, B), dcgWordList(List))).
noun_unit(Type, Event, Subj, CycLIn, CycLO, [S, T|ART], E) :-
scanDcgUntil(relationl_clause_head, Before, [S, T|ART], [Verb|Rest]),
phrase(noun_unit(Type, Event, Subj, CycLIn, CycLO1), Before, []),
(rel_clause_sem(Event, Subj, CycLO2, [Verb|Rest], E)
->
CycLO = and(CycLO1, CycLO2)
;
(CycLO = CycLO1, E=[Verb|Rest])).
noun_unit(Type, Event, Subj, CycLIn, CycLO, S, E) :-
scanDcgUntil(thePOS('Preposition'), Before, S, [Verb|Rest]),
phrase(noun_unit(Type, Event, Subj, CycLIn, CycLO1), Before, []),
(rel_clause_sem(Event, Subj, CycLO2, [Verb|Rest], E)
->
CycLO = and(CycLO1, CycLO2)
;
(CycLO = CycLO1, E=[Verb|Rest])).
noun_unit('Adjective', Event, Subj, CycLIn, CycLO) -->
theFrame(Event, 'PPCompFrameFn'('TransitivePPFrameType', Prep), 'Adjective', Template), thePrepWord(Prep),
{substEach(Template, [':SUBJECT'-Subj, ':NOUN'-Subj, ':ACTION'-Event, ':OBJECT'-Obj, ':INF-COMP'-Obj, ':OBLIQUE-OBJECT'-Obj], VerbCycL)},
noun_unit(Type, Event, Obj, and(CycLIn, VerbCycL), CycLO).
% p2c("two books on a shelf", (noun_unit(X, Y, Z, A, B), dcgWordList(List))).
noun_unit(Type, Event, Subj, CycLIn, CycLO, S, E) :-
scanDcgUntil(thePOS('Preposition'), Before, S, [Prep|Rest]),
phrase(noun_unit(Type, Event, Subj, CycLIn, CycLO1), Before, []),
(prepositional_noun_phrase(Event, Subj, Target, CycLO2, PrepWord, [Prep|Rest], E)
->
CycLO = and(CycLO1, CycLO2)
;
(CycLO = CycLO1, E=[Prep|Rest])).
%noun_unit('DET', Event, Subj, CycLIn, CycLO) -->
%noun_unit(Type, Event, Subj, CycL5, and(possessiveRelation(DET, Subj), CycL9)) -->thePOS(DET, 'Possessive'), {!}, noun_unit(Type, Event, Subj, CycL5, CycL9).
possessor_phrase(Owner, Owned, CycL5, CycL) --> dcgStartsWith(thePOS('Possessive')), subject_noun(Event, Owner, CycL5, CycL).
possessor_phrase(Owner, Owned, CycL5, CycL) --> subject_noun(Event, Owner, CycL5, CycL), theGText('\''), theGText('s').
noun_unit(Type, Event, Subj, CycL5, and(possessiveRelation(Owner, Subj), CycL9)) -->possessor_phrase(Owner, Subj, CycL8, CycL9), noun_unit(Type, Event, Subj, CycL5, CycL8).
% $100
noun_unit(Type, Event, Subj, CycLIn, and(equals(Subj, 'DollarFn'(Num)), CycLIn)) --> dollarSign, decimalNumber(Num).
% non number pronoun "I"
noun_unit(Type, Event, Subj, CycLIn, CycL9, [S|Data], E) :- phrase(thePOS('Pronoun'), [S]), not(phrase(theIsa(Subj, _, 'Number-General'), [S])), pronoun_unit(Type, Event, Subj, CycLIn, CycL9, [S|Data], E), !.
% det noun
noun_unit(Type, Event, Subj, CycLIn, CycL9, [S|Data], E) :- /*phrase(thePOS('Determiner'), [S]), */det_noun_unit(Type, Event, Subj, CycLIn, CycL9, [S|Data], E), !.
% he/BillClinton/joe's her
noun_unit(Type, Event, Subj, CycLIn, implies(CycL, CycLIn)) --> nondet_noun_unit(Type, Event, Subj, CycL).
% green thingy-like substance
noun_unit(Type, Event, Subj, CycLIn, implies(CycL, CycLIn)) --> adjective_noun_unit(Type, Event, Subj, CycL).
%noun_unit(Type, Event, Subj, CycLIn, and(equals(Subj, 'DollarFn'(Num)), CycLIn)) --> {!, fail}.
%noun_unit(Type, Event, Subj, CycL5, whp(DET, CycL9)) -->thePOS(DET, 'WHPronoun'), {!}, vp(Event, Subj, Obj, CycL5, CycL9).
%& TODO noun_unit(Type, Event, Subj, CycL5, implies(thereExists(Event2, and(actorsIn(Event2, DET, Subj), CycL9)), CycL5)) -->thePOS(DET, 'WHPronoun'), vp(Event2, Subj, Obj, CycL9).
%noun_unit(Type, Event, Subj, CycL5, and(isa(Subj, 'QuantifierFn'(DET)), CycL9)) -->thePOS(DET, 'Quantifier'), {!}, noun_unit(Type, Event, Subj, CycL5, CycL9).
noun_unit(Type, Event, Subj, CycL5, forAll(Subj, CycL9)) -->thePOS(DET, 'Quantifier'), noun_unit(Type, Event, Subj, CycL5, CycL9).
%noun_unit(Type, Event, Subj, CycL5, and(isa(Subj, 'NumberFn'(DET)), CycL9)) -->thePOS(DET, 'Number'), {!}, noun_unit(Type, Event, Subj, CycL5, CycL9).
noun_unit(Type, Event, Subj, CycL5, thereExistExactly(DET, Subj, CycL9)) -->thePOS(DET, 'Number'), noun_unit(Type, Event, Subj, CycL5, CycL9).
%noun_unit(Type, Event, Subj, CycL5, and(isa(Subj, 'DeterminerFn'(DET)), CycL9)) -->thePOS(DET, 'Determiner'), {!}, noun_unit(Type, Event, Subj, CycL5, CycL9).
noun_unit(Type, Event, Subj, CycL5, thereExists(Subj, CycL9)) -->thePOS(DET, 'Determiner'), noun_unit(Type, Event, Subj, CycL5, CycL9).
%noun_unit(Type, Event, Subj, CycL5, and(isa(Subj, 'AdjectiveFn'(DET)), CycL9)) -->thePOS(DET, 'Adjective'), {!}, noun_unit(Type, Event, Subj, CycL5, CycL9).
noun_unit(Type, Event, Subj, CycL5, and('isa'(Subj, 'AdjectiveFn'(DET)), CycL9)) -->thePOS(DET, 'Adjective'), noun_unit(Type, Event, Subj, CycL5, CycL9).
noun_unit(Type, Event, Subj, CycL5, CycL) -->subject_noun(Event, Subj, CycL5, CycL).
%noun_unit(Type, Event, Subj, CycLIn, CycL9) --> dcgAnd(scanNounUnit, noun_phrase_units(Event, Subj, CycL0, CycL9)), {!}, rel_clause_sem(Event, Subj, CycLIn, CycL0), {!}.
%subject_noun(Event, Subj, CycL5, and(isa(Subj, 'PronounFn'(DET)), CycL5)) -->thePOS(DET, 'Pronoun'), {!}.
%subject_noun(Event, Subj, CycL5, and(isa(Subj, 'ProperNounFn'(DET)), CycL9)) -->thePOS(DET, 'ProperNoun'), {!}, noun_unit(Type, Event, Subj, CycL5, CycL9).
subject_noun(Event, Subj, CycL5, and(isa(Subj, 'ProperNounFn'(DET, PN)), CycL5)) -->thePOS(DET, 'ProperNoun'), dcgAnd(thePOS(PN, 'Noun'), theName(Subj)).
%subject_noun(Event, Subj, CycL5, and(isa(Subj, 'NounFn'(PN)), CycL5)) -->thePOS(PN, 'Noun').
subject_noun(Event, Subj, CycL5, np_and(CycL, CycL5)) -->dcgAnd(dcgTemplate('NPTemplate', VarName, CycL), theName(Subj)).
% last resort
subject_noun(Event, Subj, CycL5, and(isa(Subj, 'NounFn'(PN)), CycL5)) -->dcgBoth(thePOS(PN, 'Noun'), theName(Subj)).
% =======================================================
% Proper Noun Phrases as nondet_noun_unit
% =======================================================
% his thing
nondet_noun_unit(Type, Event, Subj, CycL9) -->
dcgSeq(dcgAnd(thePOS('Possessive'), theName(HIS)), noun_unit(Type, Event, Subj, possesiveRelation(HIS, Subj), CycL9)).
% President Clinton
nondet_noun_unit(Type, Event, Subj, and(CycL1, CycL2)) --> person_title(Subj, CycL1), proper_name(Subj, CycL2).
% Clinton
nondet_noun_unit(Type, Event, Subj, CycL) --> proper_name(Subj, CycL).
% =======================================================
% Proper Noun Phrases as proper_name
% =======================================================
% Bill Clinton
proper_name(Subj, equals(Subj, 'BillClinton')) --> theTerm('BillClinton').
% Texas
proper_name(Subj, equals(Subj, CycLTerm)) -->theIsa(Subj, CycLTerm, 'Agent-Generic').
% Adjectives that are capitalized
proper_name(Subj, _)-->thePOS('Adjective'), {!, fail}.
% Van Morison
proper_name(Subj, properNameString(Subj, string(Name))) --> dcgSeq(capitalized(Text1), capitalized(Text2)), {suggestVar(Text1, Subj), flatten([Text1, Text2], Name)}.
% Fido
proper_name(Subj, properNameString(Subj, string(Name))) --> capitalized(Name), {suggestVar(Name, Subj)}.
% president
person_title(Subj, Term)--> theIsa(Subj, Term, 'PersonTypeByActivity').
% =======================================================
% Pronoun Phrases as noun_unit
% =======================================================
% Her His Your Our Their
pronoun_unit(Type, Event, Subj, CycL, and(controls(HIS, Subj), CycL9)) --> % {true}
dcgSeq(dcgAnd(thePOS('Possessive'), thePOS('Pronoun'), pronoun(HIS, CycLI, CycL9)), noun_unit(Type, Event, Subj, CycL, CycLI)).
% My
pronoun_unit(Type, Event, Subj, CycL, and(controls(HIS, Subj), CycL9)) --> % {true}
dcgSeq(dcgAnd(theWord('My-TheWord'), pronoun(HIS, CycLI, CycL9)), noun_unit(Type, Event, Subj, CycL, CycLI)).
pronoun_unit(Type, Event, Subj, CycLIn, CycL9, [S|Data], E) :- not(phrase(thePOS('Postdeterminer'), [S])), !, nonpostdet_pronoun_unit(Type, Event, Subj, CycLIn, CycL9, [S|Data], E).
% Him She They
nonpostdet_pronoun_unit(Type, Event, Subj, CycL, thereExists(Subj, CycL9)) --> pronoun(Subj, CycL, CycL9).
pronoun_unit(Type, Event, Subj, CycL, thereExists(Subj, CycL9)) --> pronoun(Subj, CycL, CycL9).
pronoun(Subj, CycL, and(isa(Subj, 'Person'), CycL)) --> theWord('I-TheWord'), {suggestVarI('Speaker', Subj)}.
pronoun(Subj, CycL, and(isa(Subj, 'Person'), CycL)) --> theWord('You-TheWord'), {suggestVarI('TargetAgent', Subj)}.
%pronoun(Subj, CycL, and(isa(Subj, 'Person'), CycL)) --> theWord('They-TheWord'), {suggestVarI('TargetAgent', Subj)}.
pronoun(Subj, CycL, and(isa(Subj, 'Male'), CycL)) --> theWord('He-TheWord'), {suggestVarI('he', Subj)}.
pronoun(Subj, CycL, and(isa(Subj, 'Female'), CycL)) --> theWord('She-TheWord'), {suggestVarI('she', Subj)}.
pronoun(Subj, CycL, and(isa(Subj, 'Artifact-NonAgentive'), CycL)) --> theWord('It-TheWord'), {suggestVarI('TargetThing', Subj)}.
%pronoun(Subj, CycL, and(Constraints, CycL)) --> dcgAnd(thePOS(Word, 'IndefinitePronoun'), theConstraints(Subj, Constraints)).
pronoun(Subj, CycL, and(Constraints, CycL)) --> theText([Text]), {pronounConstraints([Text], Subj, Constraints)}.
pronounConstraints(Text, Subj, equals(Subj, nart(Eq))):-textCached(Text, [denotation, Pos, nart(Eq)|Types]), suggestVarI(Text, Subj), !.
pronounConstraints(Text, Subj, CycL):-constraintsOnIsa(Text, Subj, CycL), !.
theConstraints(Subj, isa(Subj, ColType)) --> theText([Text]), {constraintsOnIsa([Text], Subj, ColType)}.
constraintsOnIsa(Text, Subj, CycL):-
suggestVarI(Text, Subj),
findall(and(equals(Subj, Eq), isa(Subj, Cols)), (textCached(Text, [denotation, Pos, Eq|Types]), joinCols('CollectionUnionFn', Types, Cols)), [IS|AS]),
CycL=..['#$or'|[IS|AS]].
% =======================================================
% Quantities (DET Phrases)
% =======================================================
decimalNumber(Num) --> wholeNumber(Subj, Num1), dotSign, wholeNumber(Subj, Num2), {concat_atom([Num1, '.', Num2], Atom), atom_number(Atom, Num)}.
decimalNumber(Num) --> wholeNumber(Subj, Num).
wholeNumber(Subj, Num) --> theText([Num]), {number(Num), !}.
wholeNumber(Subj, 2) --> theText([two]).
wholeNumber(Subj, 2) --> theText([two]).
wholeNumber(Subj, 1) --> theText([one]).
wholeNumber(Subj, 1) --> theText([a]).
wholeNumber(Subj, Num) --> dcgOr(theIsa(Subj, Num, 'Numeral'), theIsa(Subj, Num, 'Number-General')), {throwOnFailure(number(Num))}.
dollarSign --> thePOS('$').
dotSign --> thePOS('.').
% =======================================================
% Quantification (DET Phrases)
%
% p2c("all cars", noun_unit(X, Y, Z, A, B)).
% p2c("many cars", noun_unit(X, Y, Z, A, B)).
% p2c("large numbers of cars", noun_unit(X, Y, Z, A, B)).
% p2c("a large number of cars", noun_unit(X, Y, Z, A, B)).
% p2c("two cars", noun_unit(X, Y, Z, A, B)).
% p2c("at least two cars", noun_unit(X, Y, Z, A, B)).
% p2c("all", quant_phrase(Subj, Prop1, CycL1, CycL)).
%
% TODO Negations (no fewer than)
% =======================================================
%quant_phrase(Subj, Pre, Post, CycL) --> quant_phrase1(Subj, Pre, Mid, CycL), quant_phrase(Subj, Mid, Post, CycL).
quant_phrase(Subj, Restr, Scope, CycL9)--> dcgOr(dcgOr(existential_words, universal_words(_)), dcgNone), quant_phraseN(Subj, Restr, Scope, CycL9).
quant_phrase(Subj, Restr, Scope, 'thereExists'(Subj, 'and'(Restr , Scope))) --> existential_words.
quant_phrase(Subj, Restr, Scope, 'forAll'(Subj, 'implies'(Restr , Scope))) --> universal_words(_).
quant_phrase(Subj, Restr, Scope, CycL9) --> theFrame(_, 'QuantifierFrame', _, Template),
{substEach(Template, [':SCOPE'-Scope, ':NOUN'-Subj, ':RESTR'-Restr], CycL9)}.
quant_phrase(Subj, Restr, Scope, and(Restr, Scope)) --> [].
quant_phraseN(Subj, Restr, Scope, 'thereExistExactly'(Num, Subj, 'and'(Restr , Scope))) --> wholeNumber(Subj, Num).
quant_phraseN(Subj, Restr, Scope, 'thereExistAtLeast'(Num, Subj, 'and'(Restr , Scope))) -->
dcgSeq(at_least_words(N), wholeNumber(Subj, Num1)), {Num is N+Num1}.
%p2c("large number of", quant_phrase(Subj, Prop1, CycL1, CycL)).
quant_phraseN(Subj, Restr, Scope, and(largeNumber(Restr), Scope)) --> theText('large'), theWord('Number-TheWord'), theText('of').
% at least
at_least_words(0) --> theWord('At-TheWord'), theWord('Little-TheWord').
at_least_words(1) --> theWord('More-Than-MWW').
at_least_words(1) --> theWord('Greater-Than-MWW').
quant_phraseN(Subj, Restr, CycL1, 'thereExistAtMost'(Num, Subj, 'and'(Restr , CycL1))) -->
dcgSeq(at_most_words(N), wholeNumber(Subj, Num1)), {Num is N+Num1}.
at_most_words(0) --> dcgSeq(theWord('At-TheWord'), dcgOr(theWord('Most-TheWord'), theTerm('Most-NLAttr'))).
at_most_words(-1) --> theWord('Less-Than-MWW').
at_most_words(-1) --> theWord('Few-TheWord'), theWord('Than-TheWord').
existential_words --> existential_word, existential_word.
existential_words --> existential_word.
existential_word --> theWord('A-TheWord');theWord('An-TheWord');theWord('The-TheWord');theWord('Some-TheWord').
% there is, there are
existential_word --> theWord('There-TheWord'), theWord('Be-TheWord').
existential_word --> theWord('There-TheWord'), theWord('Exist-TheWord'). % there exists
universal_words(S) --> universal_word(_), universal_word(S).
universal_words(S) --> universal_word(S).
universal_word(plural) --> theWord('All-TheWord'), dcgOptional(existential_word).
% every
universal_word(singular) --> theTerm('Every-NLAttr').
universal_word(singular) --> theWord('Every-TheWord');theWord('Each-TheWord').
universal_word(plural) --> theWord('For-TheWord'), theWord('All-TheWord').
universal_word(plural) --> theText([forAll]).
universal_word(plural) --> theText([forall]).
% =======================================================
% Count and Mass Nouns as det_noun_unit
% =======================================================
/*
% det_noun_unit(Type, Event, Subj, CycL, thereExists(Subj, and(isa(Subj, CycL0), CycL))) --> dcgAnd(scanNounUnit, theIsa(Subj, CycL0, 'SpatialThing-Localized'), theIsa(Subj, CycLTerm, 'Collection')).
% the green party
det_noun_unit(Type, Event, Subj, equals(Subj, CycLTerm)) --> dcgOptional(theWord('The-TheWord')), proper_noun(CycLTerm).
% the usa, the green party
proper_noun(CycLTerm)--> dcgAnd(scanNounUnit, theIsa(Subj, CycLTerm, 'SpatialThing-Localized'), theIsa(Subj, CycLTerm, 'Individual')).
% the President
det_noun_unit(Type, Event, Subj, isa(Subj, CycLTerm)) --> dcgOptional(theWord('The-TheWord')), person_title(Subj, CycLTerm).
%% dog, person AuxVerb
det_noun_unit(Type, Event, Subj, CycL, and(CycL, isa(Subj, Type))) --> theIsa(Subj, Type, 'StuffType').
*/
%det_noun_unit(Type, Event, Subj, CycLVerbInfo, ('thereExists'(Subj, 'and'(AttribIsa, CycLVerbInfo)))) -->
% adjectives_phrase(Event, Subj, AttribIsa1, AttribIsa), collection_noun(Event, Subj, CycL0), adjectives_phrase(Event, Subj, CycL0, AttribIsa1).
%det_noun_unit(Type, Event, Subj, CycL1, CycL) --> quant_phrase(Subj, Prop12, CycL1, CycL), collection_noun(Event, Subj, Prop1), rel_clause_sem(Event, Subj, Prop1, Prop12).
%det_noun_unit(Type, Event, Subj, CycL1, CycL) --> quant_phrase(Subj, Prop1, CycL1, CycL), collection_noun(Event, Subj, Prop1).
det_noun_unit(Type, Event, Subj, CycLIn, CycL9) --> %{trace},
quant_phrase(Subj, AttribIsa, CycLIn, CycL9), {!},
adjective_noun_unit(Type, Event, Subj, AttribIsa).
%adjective_noun_unit(Type, Event, Subj, AttribIsa) --> collection_noun(Event, Subj, IsaInfo), thePOS('Preposition-Of'), noun_unit(Type, Event, Subj, IsaInfo, AttribIsa).
adjective_noun_unit(Type, Event, Subj, AttribIsa) --> {true},
adjectives_phrase(Event, Subj, IsaInfo, AttribIsa),
collection_noun(Event, Subj, IsaInfo).
% =======================================================
% Adjective Phrases
% =======================================================
conjuntive_and --> theText([and]).
conjuntive_and --> theText([(', ')]).
adjectives_phrase(Event, Subj, CycL, CycL9) --> thePOS('Preposition'), {!, fail}.
adjectives_phrase(Event, Subj, CycL, CycL9) --> dcgAnd(thePOS('Adjective'), adjective_word(Subj, CycL, CycLO1)), conjuntive_and, adjective_word(Subj, CycLO1, CycL9).
adjectives_phrase(Event, Subj, CycL, CycL9) --> adjective_word(Subj, CycL, CycL1), adjectives_phrase(Event, Subj, CycL1, CycL9).
adjectives_phrase(Event, Subj, CycL, CycL) --> [].
%adjective_word(Subj, CycL, and(CycL, equals(':POSSESSOR', PronounIsa), controls(PronounIsa, Subj))) --> dcgAnd(dcgAnd(thePOS('PossessivePronoun'), thePOS('Pronoun')), theIsa(Pro, PronounIsa, 'Individual')).
adjective_word(Subj, CycL, and(CycL, isa(Subj, AttribProp))) --> theIsa(Subj, AttribProp, 'ChromaticColor').
adjective_word(Subj, CycL, and(CycL, isa(Subj, AttribProp))) --> theIsa(Subj, AttribProp, 'FirstOrderCollection').
adjective_word(Subj, CycL, and(CycL, NPTemplate)) --> theFrame(_, _, 'Adjective', Template), {substEach(Template, [':NOUN'-Subj, ':REPLACE'-Subj, ':SUBJECT'-Subj], NPTemplate)}.
adjective_word(Subj, CycL, and(CycL, controls('?Speaker', Subj))) --> theWord('My-TheWord').
adjective_word(Subj, CycL, and(CycL, controls(PronounIsa, Subj))) --> dcgAnd(thePOS('PossessivePronoun'), theIsa(Pro, PronounIsa, 'Individual')).
adjective_word(Subj, CycL, and(CycL, isa(Subj, AttribProp))) --> dcgAnd(thePOS('Possessive'), theIsa(Subj, AttribProp, 'Collection')).
adjective_word(Subj, CycL, and(CycL, isa(Subj, AttribProp))) --> dcgAnd(thePOS('Adjective'), theIsa(Subj, AttribProp, 'Collection')).
% =======================================================
% Qualified Noun
% =======================================================
% dont chase prepositions
collection_noun(Event, Subj, CycL) --> thePOS('Preposition'), {!, fail}.
%':POSSESSOR'
% the eaters of the dead
collection_noun(Event, Subj, and(HowDoes, occursBefore(PreEvent, Event))) --> dcgAnd(theFrame(Subj, 'GenitiveFrame', 'AgentiveNoun', Template), theName(Subj)),
{substEach(Template, [':SUBJECT'-Subj, ':NOUN'-Subj, ':ACTION'-Event], HowDoes), suggestVar(['GenitiveFrame'], PreEvent),
ignore(sub_term(performedBy(PreEvent, Subj), HowDoes))}.
% the jugglers
collection_noun(Event, Subj, NPTemplate) --> theFrame(Subj, 'RegularNounFrame', WHPronoun, Template),
{subst(Template, ':NOUN', Subj, NPTemplate)}. %numbervars(NPTemplate, _, _)
%collection_noun(Event, Subj, Event, 'isa'(Subj, CycLCollection)) --> dcgAnd(collection_type(Subj, CycLCollection), scanNounUnit).
% the eaters of the dead
collection_noun(Event, Subj, CycLO) -->
theFrame(Subj, 'GenitiveFrame', 'CountNoun', Template),
{substEach(Template, [':SUBJECT'-Subj, ':NOUN'-Subj, ':ACTION'-Event, ':POSSESSOR'-Subj2], HowDoes)},
theWord('Of-TheWord'),
noun_unit(Type, Event, Subj2, HowDoes, CycLO).
% the men
collection_noun(Event, Subj, and(isa(Subj, CycLCollection1), isa(Subj, CycLCollection2))) -->
% dcgSeq(dcgAnd(collection_type(Subj, CycLCollection1), theName(Subj)), collection_type(Subj, CycLCollection2)).
dcgSeq(collection_type(Subj, CycLCollection1), collection_type(Subj, CycLCollection2)).
collection_noun(Event, Subj, isa(Subj, CycLCollection)) --> dcgAnd(collection_type(Subj, CycLCollection), theName(Subj)), {!}.
collection_noun(Event, Subj, equals(Subj, Type)) --> theTerm(Type).
collection_type(Subj, Type)--> theIsa(Subj, Type, 'StuffType').
collection_type(Subj, Type)--> theIsa(Subj, Type, 'ClarifyingCollectionType').
collection_type(Subj, Type)--> theIsa(Subj, Type, 'SentenceSubjectIndexical').
collection_type(Subj, 'Person') --> theText([person]).
collection_type(Subj, Type)--> theIsa(Subj, Type, 'Collection').
collection_type(Subj, 'NounFn'(Word)) --> theWord(Word, 'Noun'), {!}.
collection_type(Subj, 'AdjectiveFn'(Word)) --> theWord(Word, 'Adjective'), {!}.
collection_type(Subj, 'WordFn'(Word, POS)) --> theWord(Word, POS), {!}.
collection_type(Subj, 'Thing') --> [].
% Individual
%collection_type(Subj, 'InstanceNamedFn'(string(Word), 'WnNoun')) --> thePOS(Word, 'WnNoun').
%collection_type(Subj, 'InstanceNamedFn'(string(SType), 'Collection')) --> [Type], {flatten([Type], SType)}.
%phraseNoun_each(Eng, CycL):-posMeans(Eng, 'SimpleNoun', Form, CycL).
%phraseNoun_each(Eng, CycL):-posMeans(Eng, 'MassNoun', Form, CycL).
%phraseNoun_each(Eng, CycL):-posMeans(Eng, 'AgentiveNoun', Form, CycL).
%phraseNoun_each(Eng, CycL):-posMeans(Eng, 'Noun', Form, CycL).
%phraseNoun_each(Eng, CycL):-posMeans(Eng, 'QuantifyingIndexical', _, CycL).
% =======================================================
% Verb Phrase
% =======================================================
verb_phrase(Time, Subj, Obj, Event, CycL9, [], _):-!, fail.
verb_phrase(Time, Subj, Obj, Event, CycL9) --> [['DO'|More]], {throwOnFailure(phrase(verb_phrase(Time, Subj, Obj, Event, CycL9), More)), !}.
verb_phrase(Time, Subj, Obj, Event, CycLO)--> dcgAnd(thePOS('BeAux'), dcgIgnore(theTense(Time))),
dcgStartsWith(theForm('presentParticiple')), verb_phrase(Time, Subj, Obj, Event, CycLO).
verb_phrase(Time, Subj, Obj, Event, CycLO)--> dcgAnd(theWord('Do-TheWord'), dcgIgnore(theTense(Time))),
dcgStartsWith(dcgAnd(thePOS('Verb'), dcgIgnore(theTense(Time)))), verb_phrase(Time, Subj, Obj, Event, CycLO).
% verb_phrase(Time, Subj, Obj, Event1, CycL1), theText([(, )]), verb_phrase(Time, Subj, Obj, Event, CycL2).
%verb_phrase(Time, Subj, Obj, Event, adv(Mod, CycL9)) -->[['ADVP'|Mod]], verb_phrase(Time, Subj, Obj, Event, mod(Mod, CycL9)).
% p2c("is good", (verb_phrase(X, Y, Z, A, B), dcgWordList(List))).
verb_phrase(Time, Subj, Obj, Event, CycL9) --> dcgAnd(thePOS('BeAux'), dcgIgnore(theTense(Time))), adjectives_phrase(Event, Subj, occursDurring(Event, Time), CycL9), {!}.
verb_phrase(Time, Subj, Obj, Event, CycLO)-->verb_expression(Time, Subj, Obj, Event, CycLO).
verb_phrase(Time, Subj, Obj, Event, CycLO)-->verb_unit(Type, Time, Subj, Obj, Target, Event, CycLO).
%textCached([notice], [frame, verbSemTrans, 'TransitiveFiniteClauseFrame', 'Verb', and(':CLAUSE', notices(':SUBJECT', ':CLAUSE'))]).
% =======================================================
% Verb PRE Modifiers
% =======================================================
verb_phrase_premods(Time, Subj, Obj, Event, ScopeIn, VerbCycL) --> theFrame(Pred, 'VerbPhraseModifyingFrame', Adverb, Template),
{substEach(Template, [':SUBJECT'-Subj, ':SCOPE'-Scope, ':ACTION'-Event, ':NOUN'-Subj, ':OBJECT'-Obj], VerbCycL)},
verb_phrase_premods(Time, Subj, Obj, Event, ScopeIn, Scope).
verb_phrase_premods(Time, Subj, Obj, Event, ScopeIn, not(Scope)) --> theWord('Not-TheWord'), {!},
verb_phrase_premods(Time, Subj, Obj, Event, ScopeIn, Scope).
verb_phrase_premods(Time, Subj, Obj, Event, ScopeIn, and(VerbCycL, Scope)) --> aux_phrase(Time, Subj, Obj, Event, VerbCycL), {!},
verb_phrase_premods(Time, Subj, Obj, Event, ScopeIn, Scope).
verb_phrase_premods(Time, Subj, Obj, Event, Scope, Scope)-->[].
% =======================================================
% AuxVerbs & Adverbs
% =======================================================
aux_phrase(Time, Subj, Obj, Event, occursDurring(Event, Time)) --> dcgAnd(theWord('Have-TheWord'), dcgIgnore(theTense(Time))).
aux_phrase(Time, Subj, Obj, Event, occursDurring(Event, Time)) --> dcgAnd(thePOS('BeAux'), dcgIgnore(theTense(Time))).
aux_phrase(Time, Subj, Obj, Event, occursDurring(Event, Time)) --> dcgAnd(theWord('Be-TheWord'), dcgIgnore(theTense(Time))).
aux_phrase(Time, Subj, Obj, Event, and(occursDurring(Event, Time), bodilyDoer(Subj, Event))) --> dcgAnd(theWord('Do-TheWord'), dcgIgnore(theTense(Time))).
aux_phrase(Time, Subj, Obj, Event, behavourCapable(Subj, Event)) --> dcgAnd(theWord('Can-TheModal'), dcgIgnore(theTense(Time))).
%throwOnFailure be modal: aux_phrase(Time, Subj, Obj, Event, behavourCapable(Subj, Event)) --> dcgAnd(theWord('Can-TheWord'), dcgIgnore(theTense(Time))).
aux_phrase('Past', Subj, Obj, Event, holdsIn('Past', behavourCapable(Subj, Event))) --> theWord('Could-TheWord').
aux_phrase(Time, Subj, Obj, Event, behavourCapable(Subj, Event)) --> dcgAnd(thePOS('Modal'), dcgIgnore(theTense(Time))).
%textCached([hardly], [denotation, Pos, 'AlmostNever', 'NonNumericQuantity', 'Frequency', 'Individual']).
aux_phrase(Time, Subj, Obj, Event, isa(Event, Term)) -->dcgAnd(thePOS('Adverb'), theIsa(Event, Term, 'Individual')).
aux_phrase(Time, Subj, Obj, Event, isa(Event, 'AdverbFn'(Word))) --> dcgAnd(thePOS('Adverb'), theWord(Word)).
verb_phrase_postmods(Event, CycL, and(Truth, CycL)) -->aux_phrase(Time, Subj, Obj, Event, Truth).
verb_phrase_postmods(Event, CycL, implies(occursDuring(Event, Mod), holdsIn(Event, CycL))) --> time_phrase(Event, Mod).
verb_phrase_postmods(Event, CycL, CycL) --> [].
verb_postmods(Event, CycL, CycLO)-->verb_phrase_postmods(Event, CycL, CycLO).
%verb_postmods(Event, CycL, CycLO)-->dcgAnd(dcgNot(thePOS('Determiner')), verb_phrase_postmods(Event, CycL, CycLO)).
% Today
time_phrase(Event, Mod) --> theIsa(Event, Mod, 'TimePoint').
% Monday
time_phrase(Event, Mod) --> theIsa(Event, Mod, 'CalendarDay').
time_phrase(Event, Mod) --> theIsa(Event, Mod, 'TemporalObjectType').
time_phrase(Event, Mod) --> theIsa(Event, Mod, 'TimeInterval').
%time_phrase(Event, Mod) -->
% =======================================================
% Particles
% =======================================================
particle_np(Event, Subj, Obj, VerbCycL, VerbObjectCycL, Prep) --> partical_expression(Prep), {!}, noun_unit(Type, Event, Obj, VerbCycL, VerbObjectCycL).
particle_np(Event, Subj, Obj, VerbCycL, VerbObjectCycL, Prep) --> noun_unit(Type, Event, Obj, VerbCycL, VerbObjectCycL), partical_expression(Prep).
%e2c_sem("she took off clothing").
partical_expression(Prep) --> [['PRT'|FORM]], {(phrase(partical_expression_sub(Prep), FORM)), !}.
partical_expression(Prep) --> partical_expression_sub(Prep).
partical_expression_sub(Prep) --> thePrepWord(Prep).
% =======================================================
% Preposition
% =======================================================
prepositional_noun_phrase(Event, Obj, Target, NPCycL, Prep) -->[['PP'|SText]], {throwOnFailure(phrase(prepositional_noun_phrase(Event, Obj, Target, NPCycL, Prep), SText))}.
prepositional_noun_phrase(Event, Obj, Target, NPCycL, Prep) -->
prepositional(Event, Obj, Target, PrepCycL, Prep),
noun_unit(Type, Event, Target, PrepCycL, NPCycL).
%textCached([about], [frame, prepSemTrans, 'Post-NounPhraseModifyingFrame', 'Preposition', topicOfInfoTransfer(':ACTION', ':OBLIQUE-OBJECT')]).
prepositional(Event, Obj, Target, PrepCycL, Prep) --> %dcgAnd(thePOS(Prep, 'Preposition'), theFrame(Pred, _, 'Preposition', Template)),
dcgAnd(thePrepWord(Prep), theFrame(Pred, _, 'Preposition', Template)),
{substEach(Template, [':SUBJECT'-Obj, ':NOUN'-Obj, ':ACTION'-Event, ':OBJECT'-Target, ':OBLIQUE-OBJECT'-Target], PrepCycL)}.
thePrep(Event2, Word) --> dcgAnd(thePOS('Preposition'), theWord(Word)).
thePrepWord(Prep)-->dcgAnd(thePOS('Preposition'), theWord(Prep)).
% =======================================================
% Verbs/Verb Phrases
% =======================================================
% Two
verb_prep(Event, Subj, Obj, PTAG, Target, VerbObjectCycLO)-->
theFrame(Event, 'PPCompFrameFn'('TransitivePPFrameType', Prep), 'Verb', Template),
{phrase(thePrepWord(Prep), PTAG)},
verb_postmods(Event, VerbCycL, VerbObjectCycLO),
{substEach(Template, [':SUBJECT'-Subj, ':ACTION'-Event, ':OBJECT'-Obj, ':INF-COMP'-Target, ':OBLIQUE-OBJECT'-Target], VerbCycL)}.
% Three
verb_prep(Event, Subj, Obj, PTAG, Target, VerbObjectCycLO)-->
{phrase(thePrepWord(Prep), PTAG)},
theFrame(Event, 'PPCompFrameFn'('DitransitivePPFrameType', Prep), 'Verb', Template), %{true},
verb_postmods(Event, VerbCycL, VerbObjectCycLO),
{substEach(Template, [':SUBJECT'-Subj, ':ACTION'-Event, ':OBJECT'-Obj, ':INF-COMP'-Target, ':OBLIQUE-OBJECT'-Target], VerbCycL)}.
% Three
verb_prep(Event, Subj, Obj, PTAG, Target, and(CycL, VerbCycL))-->
theFrame(Event, 'DitransitiveNP-InfinitivePhraseFrame', 'Verb', Template), %{true},
verb_postmods(Event, VerbObjectCycL, VerbObjectCycLO),
{phrase(thePrepWord(Prep), PTAG)},
{substEach(Template, [':SUBJECT'-Subj, ':ACTION'-Event, ':OBJECT'-Obj, ':INF-COMP'-Target, ':OBLIQUE-OBJECT'-Target], VerbCycL)}.
% Three
verb_expression_resorted(Time, Subj, Obj, Event, CycLO) -->
theFrame(Event, 'DitransitiveNP-NPFrame', 'Verb', Template), %{true},
verb_postmods(Event, CycL, CycLO),
noun_unit(Type, Event, Obj, VerbObjectCycL, CycL),
dcgOptional(thePOS('Preposition')),
noun_unit(Type, Event, Target, VerbCycL, VerbObjectCycL),
{substEach(Template, [':SUBJECT'-Subj, ':ACTION'-Event, ':OBJECT'-Obj, ':INF-COMP'-Target, ':OBLIQUE-OBJECT'-Target], VerbCycL)}.
% more frames UnderstoodReciprocalObjectFrame MiddleVoiceFrame
% =======================================================
% Intransitive Verbs + verb_unit
% =======================================================
verb_expression_never(Time, Subj, Obj, Event, and(VerbObjectCycL, CycL)) -->
verb_intransitive(Time, Subj, Obj, Event, CycL),
optionalVerbGlue(_AND_OR),
verb_unit(Type, Time, Subj, Target, Obj, Event, PrepCycL),
noun_unit(Type, Event, Obj, PrepCycL, VerbObjectCycL).
% Intransitive Verbs One
verb_expression(Time, Subj, Obj, Event, CycLO) -->
verb_intransitive(Time, Subj, Obj, Event, CycL),
verb_postmods(Event, CycL9, CycLO),
intrans_modifiers(CycL, CycL9).
intrans_modifiers(CycL, CycL) --> [].
verb_intransitive(Time, Subj, Obj, Event, and(preActors(Event, Subj), CycL)) -->
theFrame(Event, 'MiddleVoiceFrame', 'Verb', Template),
{substEach(Template, [':SUBJECT'-Subj, ':ACTION'-Event], CycL)}.
verb_intransitive(Time, Subj, Obj, Event, and(preActors(Event, Subj), CycL)) -->
theFrame(Event, 'ParticleCompFrameFn'('IntransitiveParticleFrameType', Prep), Verb, Template),
thePrepWord(Prep), {!, substEach(Template, [':SUBJECT'-Subj, ':ACTION'-Event], CycL)}.
verb_intransitive(Time, Subj, Obj, Event, and(preActors(Event, Subj), CycL)) -->
theFrame(Event, 'IntransitiveVerbFrame', 'Verb', Template),
{!, substEach(Template, [':SUBJECT'-Subj, ':ACTION'-Event], CycL)}.
% =======================================================
% Verbs Expression Resorts
% =======================================================
% Verb resort Two
verb_expression(Time, Subj, Obj, Event, PREPL) -->
verb_unit(Type, Time, Subj, Obj, Target, Event, PrepCycL),
dcgOptional(thePOS(Prep, 'Preposition')),
noun_unit(Type, Event, Obj, PrepCycL, VerbObjectCycL),
{prepl(Event, VerbObjectCycL, Prep, PREPL)}.
% Verb resort Three
verb_expression(Time, Subj, Obj, Event, PREPL) -->
verb_unit(Type, Time, Subj, Obj, Target, Event, PrepCycL),
noun_unit(Type, Event, Obj, VerbTargetCycL, VerbObjectCycL),
dcgOptional(thePOS(Prep, 'Preposition')),
noun_unit(Type, Event, Target, PrepCycL, VerbTargetCycL),
{prepl(Event, VerbObjectCycL, Prep, PREPL)}.
% Verb resort One
verb_expression(Time, Subj, Obj, Event, PREPL) -->
verb_unit(Type, Time, Subj, Obj, Target, Event, PrepCycL),
dcgOptional(thePOS(Prep, 'Preposition')),
{prepl(Event, PrepCycL, Prep, PREPL)}.
prepl(Event, VerbObjectCycL, Prep, and(isa(Event, 'PrepositionFn'(Prep, Event)), VerbObjectCycL)):-nonvar(Prep), !.
prepl(Event, VerbObjectCycL, Prep, VerbObjectCycL).
% =======================================================
% Verbs Resorts
% =======================================================
%verb_unit(Type, Time, Subj, Obj, Target, Event, and(hasVAttributes(Event, AVP), CycL5)) --> auxV(AVP), verb_unit(Type, Time, Subj, Obj, Target, Event, CycL5).
%verb_unit(Type, Time, Subj, Obj, Target, Event, and(hasVAttributes(Event, AVP), CycL5)) --> adv(AVP), verb_unit(Type, Time, Subj, Obj, Target, Event, CycL5).
verb_unit(Type, Time, Subj, Obj, Target, Event, Scope) -->
verb_unit1(Type, Time, Subj, Obj, Target, Event, Scope).
verb_unit(Type, Time, Subj, Obj, Target, Event, Scope) -->
verb_phrase_premods(Time, Subj, Obj, Event, ScopeIn, Scope),
verb_unit1(Type, Time, Subj, Obj, Target, Event, ScopeIn).
% eaten by
verb_unit1(Type, Time, Subj, Obj, Target, Event, CycLO)-->
verb_resort1(Time, Obj, Subj, Target, Event, CycL), theWord('By-TheWord'), {!},
verb_postmods(Event, CycL, CycLO).
verb_unit1(Type, Time, Subj, Obj, Target, Event, CycLO)-->
verb_resort1(Time, Subj, Obj, Target, Event, CycL),
verb_postmods(Event, CycL, CycLO).
verb_unit1(Type, Time, Subj, Obj, Target, Event, CycLO)-->
verb_resort1(Time, Subj, Obj, Target, Event, CycL1),
verb_unit(Type, Time, Subj, Obj, Target, Event, CycL2),
verb_postmods(Event, and(CycL1, CycL2), CycLO).
verb_unit1(Type, Time, Subj, Obj, Target, Event, isa(Event, Isa)) --> dcgBoth((event_verb(Event, Isa), thePOS('BeAux')), theName(Event)).
verb_unit1(Type, Time, Subj, Obj, Target, Event, isa(Event, Isa)) --> dcgBoth(event_verb(Event, Isa), theName(Event)).
event_verb(Event, 'VerbAPFn'(V, P))--> thePOS(V, 'Adverb'), thePOS(P, 'Preposition'), {!}.
event_verb(Event, 'VerbVPFn'(V, P))--> thePOS(V, 'Verb'), thePOS(P, 'Preposition').
event_verb(Event, 'VerbFn'(V))-->thePOS(V, 'Verb'), {!}.
verb_resort1(Time, Subj, Obj, Target, Event, VerbCycL) --> theWord('To-TheWord'),
verb_resort1(Time, Subj, Obj, Target, Event, VerbCycL).
% Two
verb_resort1(Time, Subj, Obj, Target, Event, VerbCycL) -->
theFrame(Event, 'ParticleCompFrameFn'('TransitiveParticleNPFrameType', Prep), 'Verb', Template),
thePrepWord(Prep),
verb_postmods(Event, VerbCycL, VerbObjectCycLO),
{substEach(Template, [':SUBJECT'-Subj, ':ACTION'-Event, ':OBJECT'-Obj, ':INF-COMP'-Target, ':OBLIQUE-OBJECT'-Target], VerbCycL)}.
% Three
verb_resort1(Time, Subj, Obj, Target, Event, VerbCycL) -->
theFrame(Event, 'DitransitiveNP-NPFrame', 'Verb', Template), %{true},
{substEach(Template, [':SUBJECT'-Subj, ':ACTION'-Event, ':OBJECT'-Obj, ':INF-COMP'-Target, ':OBLIQUE-OBJECT'-Target], VerbCycL)}.
% Two
verb_resort1(Time, Subj, Obj, Target, Event, and(isa(Event, 'Event'), VerbCycL)) -->
theFrame(Event, 'TransitiveNPFrame', 'Verb', Template),
{substEach(Template, [':SUBJECT'-Subj, ':ACTION'-Event, ':OBJECT'-Obj, ':INF-COMP'-Target, ':OBLIQUE-OBJECT'-Target], VerbCycL)}.
% Three
verb_resort1(Time, Subj, Obj, Target, Event, VerbCycL) -->
theFrame(Event, _, 'Verb', Template), %{true},
{substEach(Template, [':SUBJECT'-Subj, ':ACTION'-Event, ':OBJECT'-Obj, ':INF-COMP'-Target, ':OBLIQUE-OBJECT'-Target], VerbCycL)}.
verb_resort1(Time, Subj, Obj, Target, Event, CycL) -->verb_intransitive(Time, Subj, Obj, Event, CycL).
verb_resort1(Time, Subj, Obj, Target, Event, 'is-Underspecified'(Subj, Obj)) --> dcgOr(thePOS('BeAux'), theWord('Am-TheWord'), theWord('Be-TheWord')).
verb_resort1(Time, Subj, Obj, Target, Event, and(isa(Event, EventType), occursDuring(Event, When), preActors(Event, Subj), actors(Event, Obj))) -->
dcgAnd(theIsa(Event, EventType, 'DurativeEventType'), theTense(When), theName(Event)).
verb_resort1(Time, Subj, Obj, Target, Event, and(occursDuring(Event, When), holdsIn(Event, [Pred, Subj, Obj]))) -->
dcgAnd(theIsa(Event, Pred, 'TruthFunction'), theTense(When), theName(Event)).
verb_resort1(Time, Subj, Obj, Target, Event, holdsIn(Event, PrepCycL)) --> prepositional(Event, Subj, Obj, PrepCycL, Prep).
verb_resort1(Time, Subj, Obj, Target, Event, implies(isa(Event, 'VerbFn'(Word)), eventSOT(Event, Subj, Obj, Time))) -->
dcgAnd(thePOS(Word, 'Verb'), theName(Event), theTense(Time)).
optionalVerbGlue(and) --> theText([and]).
optionalVerbGlue(or) --> theText([or]).
optionalVerbGlue(and) --> theText([, ]).
%optionalVerbGlue(and) --> [].
:-set_prolog_flag(double_quotes, string).
:- if(exists_source(logicmoo_nl_testing)).
:-include(logicmoo_nl_testing).
:- endif.
/*
, cycAssert(wordSemTrans(WORD, 33, 'Post-NounPhraseModifyingFrame', CYCL, 'Preposition', 'prepReln-Object', and(isa(':NOUN', NOUN), isa(':OBLIQUE-OBJECT', OBJECT))), '#$EnglishMt'), fail.
(implies (and (compoundSemTrans ?WORD (TheList ?S1) ?POS TransitiveInfinitivePhraseFrame ?CYCL)
(wordStrings ?WORDW ?S1) )
(wordSemTrans ?WORD 30 (PPCompFrameFn TransitiveParticleNPFrameType ?WORDW) ?CYCL ?POS compoundSemTrans True))
*/
%wordSemTrans(Word, SenseNum, Frame, CycL, Pos
%(resultIsa FrameRestrictionFn SubcategorizationFrame)
% ?SubcategorizationFrame
/*
(cyc-assert ' #$UniversalVocabularyMt)
(isa wordSemTrans NLSemanticPredicate)
(arity wordSemTrans 7)
(argIsa wordSemTrans 1 LexicalWord)
(argIsa wordSemTrans 2 Thing)
(argIsa wordSemTrans 3 Thing)
(argIsa wordSemTrans 4 Thing)
(argIsa wordSemTrans 5 LinguisticObjectType)
(argIsa wordSemTrans 6 Predicate)
(argIsa wordSemTrans 7 Thing)
(#$comment #$wordSemTrans "(#$wordSemTrans #$LexicalWord #$Integer #$SubcategorizationFrame #$NLTemplateExpression #$LinguisticObjectType #$Predicate #$NLTemplateExpression)")
(and
(implies (clauseSemTrans ?WORD ?NUM ?FRAME ?CYCL) (wordSemTrans ?WORD ?NUM ?FRAME ?CYCL Conjunction clauseSemTrans True))
(implies (nounSemTrans ?WORD ?NUM ?FRAME ?CYCL) (wordSemTrans ?WORD ?NUM ?FRAME ?CYCL Noun nounSemTrans True))
(implies
(and (denotation ?WORD ?POS ?NUM ?COL)(isa ?COL Collection)(genls ?POS Noun))
(wordSemTrans ?WORD ?NUM RegularNounFrame (isa :NOUN ?COL) ?POS denotation True))
(implies
(and (denotation ?WORD ?POS ?NUM ?COL)(isa ?COL Event)(genls ?POS Verb))
(wordSemTrans ?WORD ?NUM RegularNounFrame (and (situationConstituents :ACTION :SUBJECT)(isa :ACTION ?COL)) ?POS denotation True))
(implies (and (compoundSemTrans ?WORD (TheList ?S1) ?POS IntransitiveVerbFrame ?CYCL)
(partOfSpeech ?WORDW ?POSW ?S1) )
(wordSemTrans ?WORD 30 (PPCompFrameFn TransitiveParticleNPFrameType ?WORDW) ?CYCL ?POS compoundSemTrans True))
(implies (and (compoundSemTrans ?WORD (TheList ?S1) ?POS TransitiveNPFrame ?CYCL)
(partOfSpeech ?WORDW ?POSW ?S1) )
(wordSemTrans ?WORD 30 (PPCompFrameFn TransitiveParticleNPFrameType ?WORDW) ?CYCL ?POS compoundSemTrans True))
(implies (and (compoundSemTrans ?WORD (TheList ?S1) ?POS TransitiveInfinitivePhraseFrame ?CYCL)
(wordStrings ?WORDW ?S1) )
(wordSemTrans ?WORD 30 (PPCompFrameFn TransitiveParticleNPFrameType ?WORDW) ?CYCL ?POS compoundSemTrans True))
(implies
(prepSemTrans-New ?WORD ?POS ?FRAME ?CYCL)
(wordSemTrans ?WORD 30 ?FRAME ?CYCL ?POS prepSemTrans-New True))
(implies
(and
(nounPrep ?WORD ?PREP ?CYCL)
(termOfUnit ?PPCOMPFRAMEFN
(PPCompFrameFn TransitivePPFrameType ?PREP)))
(wordSemTrans ?WORD 30 ?PPCOMPFRAMEFN ?CYCL Noun nounPrep True))
(implies
(prepReln-Action ?ACTION ?OBJECT ?WORD ?CYCL)
(wordSemTrans ?WORD 30 VerbPhraseModifyingFrame ?CYCL Preposition prepReln-Action
(and
(isa :ACTION ?ACTION)
(isa :OBLIQUE-OBJECT ?OBJECT))))
(implies
(prepReln-Object ?NOUN ?OBJECT ?WORD ?CYCL)
(wordSemTrans ?WORD 30 Post-NounPhraseModifyingFrame ?CYCL Preposition prepReln-Object
(and
(isa :NOUN ?NOUN)
(isa :OBLIQUE-OBJECT ?OBJECT))))
(implies
(and
(semTransPredForPOS ?POS ?Pred)
(?Pred ?WORD ?NUM ?FRAME ?CYCL))
(wordSemTrans ?WORD ?NUM ?FRAME ?CYCL ?POS ?Pred True))
(implies
(adjSemTrans-Restricted ?WORD ?NUM ?FRAME ?COL ?CYCL)
(wordSemTrans ?WORD ?NUM ?FRAME ?CYCL Adjective adjSemTrans-Restricted (isa :NOUN ?COL)))
(implies
(nonCompositionalVerbSemTrans ?WORD ?COL ?CYCL)
(wordSemTrans ?WORD 666 VerbPhraseModifyingFrame ?CYCL Verb nonCompositionalVerbSemTrans (isa :OBJECT ?COL)))
(implies
(lightVerb-TransitiveSemTrans ?WORD ?COL ?CYCL)
(wordSemTrans ?WORD 667 VerbPhraseModifyingFrame ?CYCL Verb lightVerb-TransitiveSemTrans (isa :OBJECT ?COL)))
(implies
(verbSemTransPartial ?WORD ?NUM ?FRAME ?CYCL)
(wordSemTrans ?WORD ?NUM ?FRAME ?CYCL Verb verbSemTransPartial True))
(implies
(and
(isa ?OBJ ?COL)
(adjSemTransTemplate ?COL ?FRAME ?CYCL)
(denotation ?WORD Adjective ?NUM ?OBJ)
(evaluate ?TRANS
(SubstituteFormulaFn ?OBJ :DENOT ?CYCL)))
(wordSemTrans ?WORD ?NUM ?FRAME ?TRANS Adjective adjSemTrans True ))
(implies
(and
(genls ?SPEC ?COL)
(verbSemTransTemplate ?COL ?FRAME ?CYCL)
(denotation ?WORD Verb ?NUM ?SPEC)
(evaluate ?TRANS
(SubstituteFormulaFn ?SPEC :DENOT ?CYCL)))
(wordSemTrans ?WORD ?NUM ?FRAME ?TRANS Verb verbSemTrans True ))
)
(implies
(and
(relationInstanceAll performsInstancesAsPartOfJob ?REFINISHING ?REFINISHER)
(subcatFrame ?RENOVATE-THEWORD Verb ?NUM ?TRANSITIVENPFRAME)
(denotation ?RENOVATE-THEWORD AgentiveNoun ?NUM2 ?REFINISHER))
(wordSemTrans ?RENOVATE-THEWORD Verb ?TRANSITIVENPFRAME
(thereExists :ACTION
(and
(bodilyDoer :SUBJECT :ACTION)
(isa :ACTION ?REFINISHING)
(possible
(isa :SUBJECT ?REFINISHER)))) performsInstancesAsPartOfJob))
(implies
(and
(different ?WORD1 ?WORD2)
(semTransPredForPOS ?POS ?PRED)
(denotesOpposite ?WORD1 ?POS ?NUM1 ?CONCEPT)
(denotation ?WORD2 ?POS ?NUM2 ?CONCEPT)
(?PRED ?WORD2 ?NUM2 ?FRAME ?FORMULA))
(?PRED ?WORD1 ?NUM1 ?FRAME
(not ?FORMULA)))
(implies
(and
(isa ?BELIEFS BinaryPredicate)
(denotesOpposite ?DISBELIEVE-THEWORD Verb ?NUM ?BELIEFS))
(wordSemTrans ?DISBELIEVE-THEWORD Verb TransitiveNPFrame
(thereExists :ACTION
(not
(holdsIn :ACTION
(?BELIEFS :SUBJECT :OBJECT)))) denotesOpposite))
(implies
(and
(isa ?BELIEFS BinaryPredicate)
(denotation ?BELIEVE-THEWORD Verb ?NUM ?BELIEFS))
(wordSemTrans ?BELIEVE-THEWORD Verb TransitiveNPFrame
(thereExists :ACTION
(holdsIn :ACTION
(?BELIEFS :SUBJECT :OBJECT))) denotation))
(implies
(and
(isa ?BELIEFS BinaryPredicate)
(denotationRelatedTo ?BELIEVE-THEWORD Verb ?NUM ?BELIEFS))
(wordSemTrans ?BELIEVE-THEWORD Verb TransitiveNPFrame
(thereExists :ACTION
(holdsIn :ACTION
(?BELIEFS :SUBJECT :OBJECT))) denotationRelatedTo))
*/
/*
Kino's numspecs
"
(cyc-assert '
(#$implies
(#$and
(#$genls ?C #$Thing)
(#$evaluate ?R (#$EvaluateSubLFn
(#$ExpandSubLFn
(?C)
(LENGTH
(REMOVE-DUPLICATES
(ALL-SPECS ?C)))))))
(#$ist #$BaseKB (#$numspecs ?C ?R))) #$BaseKB) "*/
dm1:-e2c_sem("I see two books sitting on a shelf").
dm2:-e2c_sem("AnyTemplate1 affects the NPTemplate2").
dm3:-e2c_sem("AnyTemplate1 at AnyTemplate2").
%% ABCL tests: (progn (defconstant CHAR-CODE-LIMIT 256) (load "doit.lsp"))
% ?>
setopt:-set_prolog_flag(toplevel_print_options, [quoted(true), portray(true), max_depth(0), attributes(portray)]).
:-setopt.
| TeamSPoon/logicmoo_workspace | packs_sys/logicmoo_nlu/prolog/logicmoo_nlu/e2c/logicmoo_cyc_nl_sem.pl | Perl | mit | 145,457 |
% Compile the main Regulus code
:- compile('$REGULUS/Prolog/load').
% Load stuff, split corpus, run batch speech test on in-coverage data
:- regulus_batch('$REGULUS/Examples/Calendar/scripts/calendar_slm.cfg',
["EBL_LOAD",
"LOAD_DIALOGUE",
"SPLIT_SPEECH_CORPUS .MAIN in_coverage out_of_coverage",
"DUMP_NBEST_TRAINING_DATA_ON",
"BATCH_DIALOGUE_SPEECH in_coverage"]).
:- halt.
| TeamSPoon/logicmoo_workspace | packs_sys/logicmoo_nlu/ext/regulus/Examples/Calendar/scripts/run_speech_test_slm.pl | Perl | mit | 400 |
package DataSplitValidateHashTest1;
use strict;
use warnings;
use Test::More ();
use parent 'Test::Data::Split::Backend::ValidateHash';
my %hash = ();
sub get_hash
{
return \%hash;
}
sub run_id
{
my ( $self, $id ) = @_;
my $data = $self->lookup_data($id);
Test::More::is( $data->{a} + $data->{b}, $data->{result}, "Testing $id." );
}
sub validate_and_transform
{
my ( $self, $args ) = @_;
return 'prefix_' . $args->{data};
}
__PACKAGE__->populate(
[
test_abc => "FooBar",
test_foo => "JustAValue",
]
);
1;
| shlomif/perl-Test-Data-Split | Test-Data-Split/t/lib/DataSplitValidateHashTest1.pm | Perl | mit | 566 |
##############################################################################
# $URL: http://perlcritic.tigris.org/svn/perlcritic/trunk/distributions/Perl-Critic/lib/Perl/Critic/Policy/RegularExpressions/ProhibitComplexRegexes.pm $
# $Date: 2012-07-02 22:16:39 -0700 (Mon, 02 Jul 2012) $
# $Author: thaljef $
# $Revision: 4126 $
##############################################################################
package Perl::Critic::Policy::RegularExpressions::ProhibitComplexRegexes;
use 5.006001;
use strict;
use warnings;
use Carp;
use English qw(-no_match_vars);
use List::Util qw{ min };
use Readonly;
use Perl::Critic::Utils qw{ :booleans :severities };
use base 'Perl::Critic::Policy';
our $VERSION = '1.118';
#-----------------------------------------------------------------------------
Readonly::Scalar my $DESC => q{Split long regexps into smaller qr// chunks};
Readonly::Scalar my $EXPL => [261];
Readonly::Scalar my $MAX_LITERAL_LENGTH => 7;
Readonly::Scalar my $MAX_VARIABLE_LENGTH => 4;
#-----------------------------------------------------------------------------
sub supported_parameters {
return (
{
name => 'max_characters',
description =>
'The maximum number of characters to allow in a regular expression.',
default_string => '60',
behavior => 'integer',
integer_minimum => 1,
},
);
}
sub default_severity { return $SEVERITY_MEDIUM }
sub default_themes { return qw( core pbp maintenance ) }
sub applies_to { return qw(PPI::Token::Regexp::Match
PPI::Token::Regexp::Substitute
PPI::Token::QuoteLike::Regexp) }
#-----------------------------------------------------------------------------
sub violates {
my ( $self, $elem, $document ) = @_;
# Optimization: if its short enough now, parsing won't make it longer
return if $self->{_max_characters} >= length $elem->get_match_string();
my $re = $document->ppix_regexp_from_element( $elem )
or return; # Abort on syntax error.
$re->failures()
and return; # Abort if parse errors found.
my $qr = $re->regular_expression()
or return; # Abort if no regular expression.
my $length = 0;
# We use map { $_->tokens() } qr->children() rather than just
# $qr->tokens() because we are not interested in the delimiters.
foreach my $token ( map { $_->tokens() } $qr->children() ) {
# Do not count whitespace or comments
$token->significant() or next;
if ( $token->isa( 'PPIx::Regexp::Token::Interpolation' ) ) {
# Do not penalize long variable names
$length += min( $MAX_VARIABLE_LENGTH, length $token->content() );
} elsif ( $token->isa( 'PPIx::Regexp::Token::Literal' ) ) {
# Do not penalize long literals like \p{...}
$length += min( $MAX_LITERAL_LENGTH, length $token->content() );
} else {
# Take everything else at face value
$length += length $token->content();
}
}
return if $self->{_max_characters} >= $length;
return $self->violation( $DESC, $EXPL, $elem );
}
1;
__END__
#-----------------------------------------------------------------------------
=pod
=for stopwords BNF Tatsuhiko Miyagawa
=head1 NAME
Perl::Critic::Policy::RegularExpressions::ProhibitComplexRegexes - Split long regexps into smaller C<qr//> chunks.
=head1 AFFILIATION
This Policy is part of the core L<Perl::Critic|Perl::Critic>
distribution.
=head1 DESCRIPTION
Big regexps are hard to read, perhaps even the hardest part of Perl.
A good practice to write digestible chunks of regexp and put them
together. This policy flags any regexp that is longer than C<N>
characters, where C<N> is a configurable value that defaults to 60.
If the regexp uses the C<x> flag, then the length is computed after
parsing out any comments or whitespace.
Unfortunately the use of descriptive (and therefore longish) variable
names can cause regexps to be in violation of this policy, so
interpolated variables are counted as 4 characters no matter how long
their names actually are.
=head1 CASE STUDY
As an example, look at the regexp used to match email addresses in
L<Email::Valid::Loose|Email::Valid::Loose> (tweaked lightly to wrap
for POD)
(?x-ism:(?:[^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff]+(?![^(\040)<>@,;:".\\\[\]
\000-\037\x80-\xff])|"[^\\\x80-\xff\n\015"]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015
"]*)*")(?:(?:[^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff]+(?![^(\040)<>@,;:".\\\[
\]\000-\037\x80-\xff])|"[^\\\x80-\xff\n\015"]*(?:\\[^\x80-\xff][^\\\x80-\xff\n
\015"]*)*")|\.)*\@(?:[^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff]+(?![^(\040)<>@,
;:".\\\[\]\000-\037\x80-\xff])|\[(?:[^\\\x80-\xff\n\015\[\]]|\\[^\x80-\xff])*\]
)(?:\.(?:[^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff]+(?![^(\040)<>@,;:".\\\[\]\000
-\037\x80-\xff])|\[(?:[^\\\x80-\xff\n\015\[\]]|\\[^\x80-\xff])*\]))*)
which is constructed from the following code:
my $esc = '\\\\';
my $period = '\.';
my $space = '\040';
my $open_br = '\[';
my $close_br = '\]';
my $nonASCII = '\x80-\xff';
my $ctrl = '\000-\037';
my $cr_list = '\n\015';
my $qtext = qq/[^$esc$nonASCII$cr_list\"]/; # "
my $dtext = qq/[^$esc$nonASCII$cr_list$open_br$close_br]/;
my $quoted_pair = qq<$esc>.qq<[^$nonASCII]>;
my $atom_char = qq/[^($space)<>\@,;:\".$esc$open_br$close_br$ctrl$nonASCII]/;# "
my $atom = qq<$atom_char+(?!$atom_char)>;
my $quoted_str = qq<\"$qtext*(?:$quoted_pair$qtext*)*\">; # "
my $word = qq<(?:$atom|$quoted_str)>;
my $domain_ref = $atom;
my $domain_lit = qq<$open_br(?:$dtext|$quoted_pair)*$close_br>;
my $sub_domain = qq<(?:$domain_ref|$domain_lit)>;
my $domain = qq<$sub_domain(?:$period$sub_domain)*>;
my $local_part = qq<$word(?:$word|$period)*>; # This part is modified
$Addr_spec_re = qr<$local_part\@$domain>;
If you read the code from bottom to top, it is quite readable. And,
you can even see the one violation of RFC822 that Tatsuhiko Miyagawa
deliberately put into Email::Valid::Loose to allow periods. Look for
the C<|\.> in the upper regexp to see that same deviation.
One could certainly argue that the top regexp could be re-written more
legibly with C<m//x> and comments. But the bottom version is
self-documenting and, for example, doesn't repeat C<\x80-\xff> 18
times. Furthermore, it's much easier to compare the second version
against the source BNF grammar in RFC 822 to judge whether the
implementation is sound even before running tests.
=head1 CONFIGURATION
This policy allows regexps up to C<N> characters long, where C<N>
defaults to 60. You can override this to set it to a different number
with the C<max_characters> setting. To do this, put entries in a
F<.perlcriticrc> file like this:
[RegularExpressions::ProhibitComplexRegexes]
max_characters = 40
=head1 CREDITS
Initial development of this policy was supported by a grant from the
Perl Foundation.
=head1 AUTHOR
Chris Dolan <cdolan@cpan.org>
=head1 COPYRIGHT
Copyright (c) 2007-2011 Chris Dolan. Many rights reserved.
This program is free software; you can redistribute it and/or modify
it under the same terms as Perl itself. The full text of this license
can be found in the LICENSE file included with this module
=cut
# Local Variables:
# mode: cperl
# cperl-indent-level: 4
# fill-column: 78
# indent-tabs-mode: nil
# c-indentation-style: bsd
# End:
# ex: set ts=8 sts=4 sw=4 tw=78 ft=perl expandtab shiftround :
| amidoimidazol/bio_info | Beginning Perl for Bioinformatics/lib/Perl/Critic/Policy/RegularExpressions/ProhibitComplexRegexes.pm | Perl | mit | 7,795 |
# -*- mode: perl; coding: utf-8-unix -*-
#
# Author: Peter John Acklam
# Time-stamp: 2009-03-30 16:22:42 +02:00
# E-mail: pjacklam@online.no
# URL: http://home.online.no/~pjacklam
=pod
=head1 NAME
CompBio::SpecFun::Beta - beta, log(beta) and incomplete beta functions
=head1 SYNOPSIS
use CompBio::SpecFun::Beta qw(beta betaln betainc betaincc);
Imports all the routines explicitly. Use a subset of the list for the
routines you want.
use CompBio::SpecFun::Beta qw(:all);
Imports all the routines, as well.
=head1 DESCRIPTION
This module implements the beta function, C<beta>, the natural
logarithm of the beta function, C<betaln>, the incomplete beta
function C<betainc>, and the complement of the incomplete beta
function C<betaincc>.
For references and details about the algorithms, see below and also
see the comments inside this module.
=head1 FUNCTIONS
=over 8
=item beta A, B
Returns the beta function beta(a,b). Both A and B must be positive.
The beta function is defined as
beta(a,b) = integral from 0 to 1 of t^(a-1) * (1-t)^(b-1) dt
The following identity holds
beta(a,b) = beta(b,a)
=item betaln A, B
Returns the logarithm of the beta function log(beta(a,b)). Both A and B
must be positive. The logarithm of the beta function is defined as
betaln(a, b) = log(beta(a, b))
=item betainc X, A, B
Returns the incomplete beta function betainc(x,a,b). Both A and B must be
positive; X must be in the closed interval [0,1]. The incomplete beta
function is defined as
betainc(x,a,b) = 1 / beta(a,b) *
integral from 0 to x of t^(a-1) * (1-t)^(b-1) dt
The following identity holds
betainc(x,a,b) = 1 - betainc(1-x,b,a)
= 1 - betaincc(x,a,b)
= betaincc(1-x,b,a)
=item betaincc X, A, B
Returns the complement of the incomplete beta function
betaincc(x,a,b). Both A and B must be positive; X must be in the
closed interval [0,1]. The complement of the incomplete beta function
is defined as
betaincc(x,a,b) = 1 / beta(a,b) *
integral from x to 1 of t^(a-1) * (1-t)^(b-1) dt
The following identity holds
betaincc(x,a,b) = 1 - betaincc(1-x,b,a)
= 1 - betainc(x,a,b)
= betainc(1-x,b,a)
=back
=head1 HISTORY
=over 4
=item Version 0.01
First release.
=back
=head1 AUTHORS
Perl translation by Peter John Acklam E<lt>pjacklam@online.noE<gt>
=head1 COPYRIGHT
Copyright 2000 Peter John Acklam.
This program is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.
=cut
package CompBio::SpecFun::Beta;
require 5.000;
require Exporter;
use strict;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
use Carp;
$VERSION = '0.02';
@ISA = qw(Exporter);
@EXPORT = qw();
@EXPORT_OK = qw(beta betaln betainc);
%EXPORT_TAGS = (all => [ @EXPORT_OK ]);
# the smallest positive floating-point number such that 1+EPS > 1
# Numerical Recipes uses 3.0e-7
use constant EPS => 2.220446049250313080847263336181640625e-016;
# the smallest positive normalized floating point number
# Numerical Recipes uses 1.0e-30
use constant FPMIN => 2.2250738585072e-308;
# largest number of iterations we allow
use constant MAXIT => 1000;
########################################################################
## Internal functions.
########################################################################
########################################################################
# Evaluates continued fraction for incomplete beta function by
# modified Lentz's method (sec 5.2 in Numerical Recipes).
########################################################################
sub _betacf ($$$) {
# This is an internal function, so we omit error checking of args.
my ($x, $a, $b) = @_;
# These q's will be used in factors that occur
# in the coefficients (6.4.6).
my $qab = $a+$b;
my $qap = $a+1;
my $qam = $a-1;
my $c = 1; # First step of Lentz's method.
my $d = 1-$qab*$x/$qap;
if (abs($d) < FPMIN) { $d = FPMIN; }
$d = 1/$d;
my $h = $d;
my $m;
for ( $m = 1; $m <= MAXIT; $m++ ) {
my $m2 = 2*$m;
my $aa = $m*($b-$m)*$x/(($qam+$m2)*($a+$m2));
$d = 1+$aa*$d; # One step (the even one) of the recurrence.
if (abs($d) < FPMIN) { $d = FPMIN; }
$c = 1+$aa/$c;
if (abs($c) < FPMIN) { $c = FPMIN; }
$d = 1/$d;
$h *= $d*$c;
$aa = -($a+$m)*($qab+$m)*$x/(($a+$m2)*($qap+$m2));
$d = 1+$aa*$d; # Next step of the recurrence (the odd one).
if (abs($d) < FPMIN) { $d = FPMIN; }
$c = 1+$aa/$c;
if (abs($c) < FPMIN) { $c = FPMIN; }
$d = 1/$d;
my $del = $d*$c;
$h *= $del;
if (abs($del-1) < EPS) { last; } # Are we done?
}
if ($m > MAXIT) {
die "a or b too big, or MAXIT too small in _betacf";
}
return $h;
}
########################################################################
## User functions.
########################################################################
########################################################################
# Beta function
#
# Reference: Abramowitz & Stegun, Handbook of Mathematical Functions,
# sec. 6.2.
########################################################################
sub beta {
# Get and check input arguments.
croak "usage: beta(a,b)\n" unless @_ == 2;
my ($a, $b) = @_;
croak "Both arguments to beta must be positive"
unless $a > 0 && $b > 0;
# Special cases.
return 1/$b if $a == 1;
return 1/$a if $b == 1;
# The general case.
require CompBio::SpecFun::Gamma;
import CompBio::SpecFun::Gamma qw(gammaln);
return exp( gammaln($a) + gammaln($b) - gammaln($a+$b) );
}
########################################################################
# Logarithm of beta function.
#
# Reference: Abramowitz & Stegun, Handbook of Mathematical Functions,
# sec. 6.2.
########################################################################
sub betaln {
# Get and check input arguments.
croak "usage: betaln(a,b)\n" unless @_ == 2;
my ($a, $b) = @_;
croak "Both arguments to betaln must be positive"
unless $a > 0 && $b > 0;
# Special cases.
return -log($b) if $a == 1;
return -log($a) if $b == 1;
# The general case.
require CompBio::SpecFun::Gamma;
import CompBio::SpecFun::Gamma qw(gammaln);
return gammaln($a) + gammaln($b) - gammaln($a+$b);
}
########################################################################
# Incomplete beta function.
#
# Reference: Abramowitz & Stegun, Handbook of Mathematical Functions,
# sec. 26.5.
########################################################################
sub betainc {
# Get and check input arguments.
croak "usage: betainc(x,a,b)\n" unless @_ == 3;
my ($x, $a, $b) = @_;
croak "First argument must be in the interval [0,1]"
if $x < 0 || $x > 1;
croak "Last two arguments must be positive" unless $a > 0 && $b > 0;
# Special cases.
return 0 if $x == 0;
return 1 if $x == 1;
return $x**$a if $b == 1;
return 1 - (1 - $x)**$b if $b == 1;
return 0.5 if $x == 0.5 && $a == $b;
# The general case.
require CompBio::SpecFun::Gamma;
import CompBio::SpecFun::Gamma qw(gammaln);
# Factors in front of the continued fraction.
my $bt = exp( gammaln($a + $b) - gammaln($a) - gammaln($b)
+ $a*log($x) + $b*log(1 - $x) );
if ( $x < ($a+1)/($a+$b+2) ) {
# Use continued fraction directly.
return $bt * _betacf($x, $a, $b) / $a;
} else {
# Use continued fraction after making the symmetry
# transformation.
return 1 - $bt * _betacf(1 - $x, $b, $a) / $b;
}
}
########################################################################
# The complement of the incomplete beta function.
########################################################################
sub betaincc {
# Get and check input arguments.
croak "usage: betaincc(x,a,b)\n" unless @_ == 3;
my ($x, $a, $b) = @_;
croak "First argument must be in the interval [0,1]"
if $x < 0 || $x > 1;
croak "Last two arguments must be positive" unless $a > 0 && $b > 0;
# Special cases.
return 1 if $x == 0;
return 0 if $x == 1;
return 1 - $x**$a if $b == 1;
return (1 - $x)**$b if $b == 1;
return 0.5 if $x == 0.5 && $a == $b;
# The general case.
require CompBio::SpecFun::Gamma;
import CompBio::SpecFun::Gamma qw(gammaln);
# Factors in front of the continued fraction.
my $bt = exp( gammaln($a + $b) - gammaln($a) - gammaln($b)
+ $a*log($x) + $b*log(1 - $x) );
if ( $x < ($a+1)/($a+$b+2) ) {
return 1 - $bt * _betacf($x, $a, $b) / $a;
} else {
return $bt * _betacf(1 - $x, $b, $a) / $b;
}
}
1; # Modules must return true.
| bartongroup/profDGE48 | Modules/Beta.pm | Perl | mit | 9,118 |
No information available about domain name umpirsky-wisdom.pl in the Registry NASK database.
WHOIS displays data with a delay not exceeding 15 minutes in relation to the .pl Registry system
Registrant data available at http://dns.pl/cgi-bin/en_whois.pl
| umpirsky/wisdom | tests/Wisdom/Fixtures/whois/umpirsky-wisdom.pl | Perl | mit | 258 |
=head
Copyright (c) 2014 Dennis Hoppe
www.dennis-hoppe.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
=cut
use strict;
use warnings;
use AnyEvent;
use DBI;
use Net::RabbitFoot;
use RunnerDB;
use Avro::Schema;
use Avro::BinaryEncoder;
use Avro::BinaryDecoder;
use IO::String;
use Data::Dumper;
# (1) Initialize the connection to RabbitMQ using the 'running_queue'
my $Connection = Net::RabbitFoot->new()->load_xml_spec()->connect(
host => 'localhost',
port => 5672,
user => 'guest',
pass => 'guest',
vhost => '/',
);
my $Channel = $Connection->open_channel();
$Channel->declare_queue(queue => 'running_queue');
# (2) Handle incoming requests
# - Note, that we don't perform any error handling for simplicity's sake
sub serve {
print " [>] Incoming request ...\n";
my $Data = shift;
my $Payload = $Data->{body}->{payload};
my $Properties = $Data->{header};
# (a) Map the incoming request to the required RunRequest
open FILEHANDLE, '../resources/RunRequest.avsc' or die $!;
my $RunRequest = do { local $/; <FILEHANDLE> };
close(FILEHANDLE);
my $AvroSchema = Avro::Schema->parse($RunRequest);
my $Reader = IO::String->new($Payload);
my $Request = Avro::BinaryDecoder->decode(
writer_schema => $AvroSchema,
reader_schema => $AvroSchema,
reader => $Reader,
);
my $UserId = $Request->{UserRef}->{id};
# (b) Configure a (mock) database to retrieve runs done by $User
my $dbh = DBI->connect('dbi:Mock:', '', '');
my $Statement = <<"END_SQL";
SELECT r.alias, r.id, r.distanceMeters
FROM Run as r
WHERE r.userId = 1;
END_SQL
my @ResultSet = (
['alias', 'id', 'distanceMeters'],
['Hamburg Run', 1, 3200],
['Alster Run', 2, 4600],
);
$dbh->{mock_add_resultset} = \@ResultSet;
# (c) Perform database call to get a list of runs
print " [-] Retrieve runs ...\n";
my $Database = new RunnerDB($dbh);
my $RunsFromDB = $Database->getRunsByUserId($UserId);
# (d) Iterate over result set while building the response
my @Runs;
foreach my $Run (@{$RunsFromDB}) {
my %RunAvro = (
nameOrAlias => $Run->{'Alias'},
distanceMeters => $Run->{'Distance'},
);
push @Runs, \%RunAvro;
}
my %Response = (
runs => \@Runs,
);
# (e) Serialize the response object (binary format)
$Payload = undef;
open FILEHANDLE, '../resources/Run.avsc' or die $!;
my $Run = do { local $/; <FILEHANDLE> };
close(FILEHANDLE);
my $AAvroSchema = Avro::Schema->parse($Run);
Avro::BinaryEncoder->encode(
schema => $AAvroSchema,
data => \%Response,
emit_cb => sub { $Payload .= ${ $_[0] } },
);
# (f) Publish the result to the queue
print ' [<] Send response containing ' . @{$Response{runs}} . " runs \n";
$Channel->publish(
exchange => '',
routing_key => $Properties->{reply_to},
header => {
correlation_id => $Properties->{correlation_id},
},
body => $Payload,
);
$Channel->ack();
}
$Channel->qos(prefetch_count => 1);
$Channel->consume(
on_consume => \&serve,
);
print " [x] Awaiting RPC requests\n";
# Let's wait for requests ...
AnyEvent->condvar->recv;
1;
| hopped/rabbitmq-avro | src/main/perl/RPCServer.pl | Perl | mit | 4,287 |
#!/usr/bin/perl
use File::Copy;
use strict;
use warnings;
use Cwd;
my $dst = "C:/Users/jnhuy/Nextcloud/HR Profile/";
my $dir = cwd();
opendir(DIR, $dir);
my @files = readdir(DIR);
closedir(DIR);
if ( ! -d $dst )
{
print ( $dst . " does not exist" );
exit(-1);
}
foreach my $f (@files) {
if ($f =~ /(\w+)-.*\.pdf/)
{
my $who = $1;
print ("move $f to $dst $who\n");
move($f, $dst . $who . "/Paystubs");
}
}
| mrjohnnyhuynh/scripts | movehr.pl | Perl | mit | 458 |
package O2;
use strict;
use base 'Exporter';
our @EXPORT_OK = qw($context $o2 $cgi $db $config $session $CONTEXT $O2 $CGI $DB $CONFIG $SESSION);
our ($context, $o2, $cgi, $db, $config, $session); # Use lowercase
our ($CONTEXT, $O2, $CGI, $DB, $CONFIG, $SESSION); # or uppercase
my %DEBUG_TYPE; # Key: caller-package
BEGIN {
if (exists $ENV{MOD_PERL}) {
require O2::Dispatch::ModPerlGlobals::Context;
require O2::Dispatch::ModPerlGlobals::Cgi;
require O2::Dispatch::ModPerlGlobals::Db;
require O2::Dispatch::ModPerlGlobals::Config;
require O2::Dispatch::ModPerlGlobals::Session;
tie $context, 'O2::Dispatch::ModPerlGlobals::Context';
tie $o2, 'O2::Dispatch::ModPerlGlobals::Context';
tie $cgi, 'O2::Dispatch::ModPerlGlobals::Cgi';
tie $db, 'O2::Dispatch::ModPerlGlobals::Db';
tie $config, 'O2::Dispatch::ModPerlGlobals::Config';
tie $session, 'O2::Dispatch::ModPerlGlobals::Session';
tie $CONTEXT, 'O2::Dispatch::ModPerlGlobals::Context';
tie $O2, 'O2::Dispatch::ModPerlGlobals::Context';
tie $CGI, 'O2::Dispatch::ModPerlGlobals::Cgi';
tie $DB, 'O2::Dispatch::ModPerlGlobals::Db';
tie $CONFIG, 'O2::Dispatch::ModPerlGlobals::Config';
tie $SESSION, 'O2::Dispatch::ModPerlGlobals::Session';
}
}
#-----------------------------------------------------------------------------
sub import {
my ($package, @symbolsToImport) = @_;
my %symbolsToImport = map { lc ($_) => 1 } @symbolsToImport;
if (!$O2::context) { # Probably a script, so let's not tie STDOUT when we create context:
require O2::Cgi;
require O2::Context;
$O2::context = O2::Context->new( cgi => O2::Cgi->new(tieStdout => 'no') );
}
$context = $O2::context if $symbolsToImport{'$context'};
$CONTEXT = $O2::context if $symbolsToImport{'$CONTEXT'};
$o2 = $O2::context if $symbolsToImport{'$o2'};
$O2 = $O2::context if $symbolsToImport{'$O2'};
$context->setSession( $context->getSingleton('O2::Session') ) if $symbolsToImport{'$session'} && !$session && !$context->getSession();
if (!$ENV{MOD_PERL}) {
$cgi = $CGI = $context->getCgi() if !$cgi && $symbolsToImport{'$cgi'};
$db = $DB = $context->getDbh() if !$db && $symbolsToImport{'$db'};
$config = $CONFIG = $context->getConfig() if !$config && $symbolsToImport{'$config'};
$session = $SESSION = $context->getSession() if !$session && $symbolsToImport{'$session'};
}
# Enable debugging:
my ($callerPackage) = caller;
my $debugLevel = $main::debugLevel;
my $debugType;
if (!$debugLevel) {
# Check if DEBUG has been set (with "use constant") in the calling package (must be set before O2 is used):
{
no strict;
eval "\$debugLevel = ${callerPackage}::DEBUG";
}
die $@ if $@;
$debugLevel = 0 if $debugLevel =~ m{ DEBUG }xms; # If the constant doesn't exist in the calling package...
}
# Check if DEBUG_TYPE has been set (with "use constant") in the calling package (must be set before O2 is used):
{
no strict;
eval "\$debugType = ${callerPackage}::DEBUG_TYPE";
}
die $@ if $@;
# Log to database by default
$debugType = 'db' if exists $DEBUG_TYPE{$callerPackage} && $DEBUG_TYPE{$callerPackage} =~ m{ DEBUG_TYPE }xms; # If the constant doesn't exist in the calling package...
$debugType ||= 'db';
$DEBUG_TYPE{$callerPackage} = $debugType;
{
no strict 'refs';
*{"${callerPackage}::debug"}
= $debugLevel == 1 ? \&_debug1
: $debugLevel == 2 ? \&_debug2
: $debugLevel >= 3 ? \&_debug
: sub {}
;
}
# Enable logging of info and warnings to O2_CONSOLE_LOG ("warn" still logs to the error-log file):
{
no strict 'refs';
*{"${callerPackage}::loginfo"} = \&_logInfo;
*{"${callerPackage}::warning"} = \&_logWarning;
}
O2->export_to_level(1, @_);
}
#-----------------------------------------------------------------------------
sub _debug1 {
my ($msg, $level) = @_;
return if $level && $level > 1;
_debug($msg);
}
#-----------------------------------------------------------------------------
sub _debug2 {
my ($msg, $level) = @_;
return if $level && $level > 2;
_debug($msg);
}
#-----------------------------------------------------------------------------
sub _debug3 {
my ($msg, $level) = @_;
_debug($msg);
}
#-----------------------------------------------------------------------------
sub _debug {
my ($msg) = @_;
my ($callerPackage) = caller;
return warn $msg if $DEBUG_TYPE{$callerPackage} eq 'warn';
eval {
$O2::context->getConsole()->_debug($msg, callerLevel => 4);
};
warn "Couldn't log debug message <<$msg>>: $@" if $@;
}
#-----------------------------------------------------------------------------
sub _logWarning {
my ($msg, %params) = @_;
eval {
$O2::context->getConsole()->_warning($msg, %params, callerLevel => 3);
};
warn "Couldn't log warning <<$msg>>: $@" if $@;
}
#-----------------------------------------------------------------------------
sub _logInfo {
my ($msg, %params) = @_;
eval {
$O2::context->getConsole()->_message($msg, %params);
};
warn "Couldn't log info message <<$msg>>: $@" if $@;
}
#-----------------------------------------------------------------------------
1;
| haakonsk/O2-Framework | lib/O2.pm | Perl | mit | 5,339 |
transfer_lexicon([utterance_type, command], [utterance_type, command]).
transfer_lexicon([utterance_type, query], [utterance_type, query]).
transfer_lexicon([state, be], [state, vara]).
transfer_lexicon([action, dim], [action, vrid_ner]).
macro(light_dependent_rule(From, LightVersion, NonLightVersion),
( transfer_rule(From, LightVersion) :- context([device, light]) )
).
macro(light_dependent_rule(From, LightVersion, NonLightVersion),
( transfer_rule(From, NonLightVersion) :- \+ context([device, light]) )
).
@light_dependent_rule([[action, switch_on]], [[action, tända]], [[action, sätta_på]]).
@light_dependent_rule([[action, switch_off]], [[action, släck]], [[action, stänga_av]]).
@light_dependent_rule([[onoff, on]], [[onoff, tänd]], [[onoff, på]]).
@light_dependent_rule([[onoff, off]], [[onoff, släckt]], [[onoff, av]]).
transfer_lexicon([device, light], [device, lampa]).
transfer_lexicon([device, fan], [device, fläkt]).
transfer_lexicon([location, kitchen], [location, kök]).
transfer_lexicon([location, living_room], [location, vardagsrum]).
| TeamSPoon/logicmoo_workspace | packs_sys/logicmoo_nlu/ext/regulus/Examples/Toy1/Prolog/interlingua_to_swe.pl | Perl | mit | 1,088 |
#!/usr/bin/perl -W
use strict;
use warnings 'all';
use CGI;
#use utf8;
my $cgi = new CGI;
print $cgi->header(-type => "image/png");
#print $cgi->header();
use CGI::Carp 'fatalsToBrowser';
use JSON;
use File::Path qw{mkpath}; # make_path
use GD;
use Encode;
#use GD::Simple;
# create a new image
sub calculate_max_font_size
{
my ($font, $string, $image_width, $image_height) = @_;
my $max_font_width = 1;
my $width = 0;
my $height = 0;
my @bounds;
for(1..100)
{
my $fs = $_ + 1;
my $im = new GD::Image($image_width, $image_height);
# allocate some colors
my $white = $im->colorAllocate(255,255,255);
my $black = $im->colorAllocate(0,0,0);
# make the background transparent and interlaced
$im->transparent($white);
$im->interlaced('true');
@bounds = $im->stringFT($black, $font, $fs, 0, 0, $fs, $string);
#print 'font size: ' . $fs . '<br>';
#print $bounds[0] . ' - ' . $bounds[1] . ' - Lower left corner (x,y)<br>'; #
#print $bounds[2] . ' - ' . $bounds[3] . ' - Lower right corner (x,y)<br>'; #Lower right corner (x,y)
#print $bounds[4] . ' - ' . $bounds[5] . ' - Upper right corner (x,y)<br>'; #Upper right corner (x,y)
#print $bounds[6] . ' - ' . $bounds[7] . ' - Upper left corner (x,y)<br>'; #
#print $bounds[2] . ' - right corner (x)<br>'; #Lower right corner (x,y)
#print '--------------------------<br><br>';
$width = $bounds[2] - $bounds[0];
$height = $bounds[3] - $bounds[5];
#font size: 32
#-3 - 66 - Lower left corner (x,y)
#442 - 66 - Lower right corner (x,y)
#442 - -11 - Upper right corner (x,y)
#-3 - -11 - Upper left corner (x,y)
$max_font_width = $fs;
$bounds[8] = $max_font_width;
if($width >= $image_width)
{
last;
}
if($height >= ( $image_height ))
{
last;
}
}
return @bounds;
}
sub generate_image
{
my($string, $image_width, $image_height, $font) = @_;
my @bounds = calculate_max_font_size($font, $string, $image_width, $image_height);
my $max_font_size = $bounds[8];
#print $max_font_size;
#exit;
#$width = $bounds[2] - $bounds[0];
#$height = $bounds[3] - $bounds[5];
my $im = new GD::Image($image_width, $image_height);
my $white = $im->colorAllocate(255,255,255);
my $black = $im->colorAllocate(0,0,0);
$im->transparent($white);
$im->interlaced('true');
$im->stringFT($black, $font, $max_font_size, 0, ( (-1) * ($bounds[0]) ), ( $max_font_size - ( $bounds[5] ) ), $string);
binmode STDOUT;
print $im->png;
}
generate_image('Mark livings', 400, 100, 'fonts/Signerica_Fat.ttf');
#print calculate_max_font_size('fonts/Signerica_Fat.ttf', 'Mark livings', 440, 100); | dimpu/AravindCom | FormBuilder/js/signature_component/processors/gd2.pl | Perl | mit | 2,657 |
# File: ParseDate.pm
#
# Purpose: Just a simple interface to test/play with PBot::Core::Utils::ParseDate
# and make sure it's working properly.
#
# SPDX-FileCopyrightText: 2021 Pragmatic Software <pragma78@gmail.com>
# SPDX-License-Identifier: MIT
package PBot::Plugin::ParseDate;
use parent 'PBot::Plugin::Base';
use PBot::Imports;
use Time::Duration qw/duration/;
sub initialize {
my ($self, %conf) = @_;
$self->{pbot}->{commands}->add(
name => 'pd',
help => 'Simple command to test ParseDate interface',
subref =>sub { return $self->cmd_parsedate(@_) },
);
}
sub unload {
my $self = shift;
$self->{pbot}->{commands}->remove('pd');
}
sub cmd_parsedate {
my ($self, $context) = @_;
my ($seconds, $error) = $self->{pbot}->{parsedate}->parsedate($context->{arguments});
return $error if defined $error;
return duration $seconds;
}
1;
| pragma-/pbot | lib/PBot/Plugin/ParseDate.pm | Perl | mit | 905 |
# !!!!!!! 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';
V46
37
38
162
163
176
177
1545
1548
1642
1643
2546
2548
2553
2554
3449
3450
8240
8248
8359
8360
8374
8375
8379
8380
8382
8383
8451
8452
8457
8458
43064
43065
65020
65021
65130
65131
65285
65286
65504
65505
73693
73697
126124
126125
126128
126129
END
| operepo/ope | client_tools/svc/rc/usr/share/perl5/core_perl/unicore/lib/Lb/PO.pl | Perl | mit | 733 |
# 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::Enums::OfflineUserDataJobStatusEnum;
use strict;
use warnings;
use Const::Exporter enums => [
UNSPECIFIED => "UNSPECIFIED",
UNKNOWN => "UNKNOWN",
PENDING => "PENDING",
RUNNING => "RUNNING",
SUCCESS => "SUCCESS",
FAILED => "FAILED"
];
1;
| googleads/google-ads-perl | lib/Google/Ads/GoogleAds/V9/Enums/OfflineUserDataJobStatusEnum.pm | Perl | apache-2.0 | 885 |
=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::BlastGenscanDNA -
=head1 SYNOPSIS
my $blast = Bio::EnsEMBL::Analysis::RunnableDB::BlastGenscanDNA->
new(
-analysis => $analysis,
-db => $db,
-input_id => 'contig::AL1347153.1.3517:1:3571:1'
);
$blast->fetch_input;
$blast->run;
my @output =@{$blast->output};
=head1 DESCRIPTION
This module inherits from the Blast runnable and instantiates
BlastTranscriptDNA passing in prediction transcript
=head1 METHODS
=cut
package Bio::EnsEMBL::Analysis::RunnableDB::BlastGenscanDNA;
use strict;
use warnings;
use Bio::EnsEMBL::Analysis::Runnable::BlastTranscriptDNA;
use Bio::EnsEMBL::Analysis::RunnableDB::Blast;
use Bio::EnsEMBL::Utils::Exception qw(throw warning);
use Bio::EnsEMBL::Analysis::Config::General;
use Bio::EnsEMBL::Analysis::Config::Blast;
use vars qw(@ISA);
@ISA = qw(Bio::EnsEMBL::Analysis::RunnableDB::Blast);
=head2 fetch_input
Arg [1] : Bio::EnsEMBL::Analysis::RunnableDB::BlastGenscanDNA
Function : fetch sequence and prediction transcripts of database,
read config files instantiate the filter, parser and finally the blast
runnables
Returntype: none
Exceptions: none
Example :
=cut
sub fetch_input{
my ($self) = @_;
my $slice = $self->fetch_sequence($self->input_id, $self->db);
$self->query($slice);
my %blast = %{$self->BLAST_PARAMS};
my $logic_names = $BLAST_AB_INITIO_LOGICNAME;
my @pts ;
my $pta = $self->db->get_PredictionTranscriptAdaptor;
$logic_names = ['Genscan'] if(scalar(@$logic_names) == 0);
foreach my $logic_name (@$logic_names) {
my $pt = $pta->fetch_all_by_Slice($self->query, $logic_name);
push @pts, @$pt ;
}
my $parser = $self->make_parser;
my $filter;
if($self->BLAST_FILTER){
$filter = $self->make_filter;
}
foreach my $t(@pts){
my $runnable = Bio::EnsEMBL::Analysis::Runnable::BlastTranscriptDNA->
new(
-transcript => $t,
-query => $self->query,
-program => $self->analysis->program_file,
-parser => $parser,
-filter => $filter,
-database => $self->analysis->db_file,
-analysis => $self->analysis,
%blast,
);
$self->runnable($runnable);
}
}
| Ensembl/ensembl-analysis | modules/Bio/EnsEMBL/Analysis/RunnableDB/BlastGenscanDNA.pm | Perl | apache-2.0 | 3,237 |
package TestCGI;
use Moose;
use JSON;
use Data::Dumper;
use Log::Log4perl qw(:easy);
use URI::Escape;
use LWP::UserAgent;
has json => (
is => 'rw',
isa => 'Object',
default => sub { return JSON->new()->utf8; }
);
has wf_token => (
is => 'rw',
isa => 'Str',
lazy => 1,
default => ''
);
has session_id => (
is => 'rw',
isa => 'Str',
lazy => 1,
default => ''
);
sub update_rtoken {
my $self = shift;
my $result = $self->mock_request({'page' => 'bootstrap!structure'});
my $rtoken = $result->{rtoken};
$self->rtoken( $rtoken );
return $rtoken;
}
has rtoken => (
is => 'rw',
isa => 'Str',
lazy => 1,
default => ''
);
sub mock_request {
my $self = shift;
my $data = shift;
if (exists $data->{wf_token} && !$data->{wf_token}) {
$data->{wf_token} = $self->wf_token();
}
my $ua = LWP::UserAgent->new;
my $server_endpoint = 'http://localhost/cgi-bin/webui.fcgi';
$ua->default_header( 'Accept' => 'application/json' );
$ua->default_header( 'X-OPENXPKI-Client' => 1);
if ($self->session_id()) {
$ua->default_header( 'Cookie' => 'oxisess-webui='.$self->session_id() );
}
# always use POST for actions
my $res;
if ($data->{action}) {
# add XSRF token
if (!exists $data->{_rtoken}) {
$data->{_rtoken} = $self->rtoken();
}
$ua->default_header( 'content-type' => 'application/x-www-form-urlencoded');
$res = $ua->post($server_endpoint, $data);
} else {
my $qsa = '?';
map { $qsa .= sprintf "%s=%s&", $_, uri_escape($data->{$_}); } keys %{$data};
$res = $ua->get( $server_endpoint.$qsa );
}
# Check the outcome of the response
if (!$res->is_success) {
warn $res->status_line;
return {};
}
if ($res->header('Content-Type') !~ /application\/json/) {
return $res->content;
}
my $json = $self->json()->decode( $res->content );
if (ref $json->{main} && $json->{main}->[0]->{content}->{fields}) {
map { $self->wf_token($_->{value}) if ($_->{name} eq 'wf_token') } @{$json->{main}->[0]->{content}->{fields}};
}
if (my $cookie = $res->header('Set-Cookie')) {
if ($cookie =~ /oxisess-webui=([^;]+);/) {
$self->session_id($1);
}
}
return $json;
}
# Static call that generates a ready-to-use client
sub factory {
my $client = TestCGI->new();
$client->update_rtoken();
$client ->mock_request({ page => 'login'});
$client ->mock_request({
'action' => 'login!stack',
'auth_stack' => "Testing",
});
$client ->mock_request({
'action' => 'login!password',
'username' => 'raop',
'password' => 'openxpki'
});
# refetch new rtoken, also inits session via bootstrap
$client->update_rtoken();
return $client;
}
1;
| aleibl/openxpki | qatest/lib/TestCGI.pm | Perl | apache-2.0 | 2,928 |
#
# 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 database::redis::mode::replication;
use base qw(centreon::plugins::templates::counter);
use strict;
use warnings;
use centreon::plugins::templates::catalog_functions qw(catalog_status_threshold_ng);
sub custom_status_output {
my ($self, %options) = @_;
my $msg = sprintf("Node role is '%s' [cluster: %s]", $self->{result_values}->{role}, $self->{result_values}->{cluster_state});
if ($self->{result_values}->{role} eq 'slave') {
$msg .= sprintf(
" [link status: %s] [sync status: %s]",
$self->{result_values}->{link_status}, $self->{result_values}->{sync_status}
);
}
return $msg;
}
sub set_counters {
my ($self, %options) = @_;
$self->{maps_counters_type} = [
{ name => 'global', type => 0, skipped_code => { -10 => 1 } },
{ name => 'master', type => 0, skipped_code => { -10 => 1 } },
{ name => 'slave', type => 0, skipped_code => { -10 => 1 } }
];
$self->{maps_counters}->{global} = [
{
label => 'status',
type => 2,
warning_default => '%{sync_status} =~ /in progress/i',
critical_default => '%{link_status} =~ /down/i',
set => {
key_values => [ { name => 'link_status' }, { name => 'sync_status' }, { name => 'role' }, { name => 'cluster_state' } ],
closure_custom_output => $self->can('custom_status_output'),
closure_custom_perfdata => sub { return 0; },
closure_custom_threshold_check => \&catalog_status_threshold_ng
}
},
{ label => 'connected-slaves', nlabel => 'replication.slaves.connected.count', set => {
key_values => [ { name => 'connected_slaves' } ],
output_template => 'number of connected slaves: %s',
perfdatas => [
{ template => '%s', min => 0 }
]
}
}
];
$self->{maps_counters}->{master} = [
{ label => 'master-repl-offset', nlabel => 'replication.master.offset.count', set => {
key_values => [ { name => 'master_repl_offset' } ],
output_template => 'master replication offset: %s',
perfdatas => [
{ template => '%s', min => 0 }
]
}
}
];
$self->{maps_counters}->{slave} = [
{ label => 'master-last-io', nlabel => 'replication.master.last_interaction.seconds', set => {
key_values => [ { name => 'master_last_io_seconds_ago' } ],
output_template => 'last interaction with master: %s s',
perfdatas => [
{ template => '%s', min => 0, unit => 's' }
]
}
},
{ label => 'slave-repl-offset', nlabel => 'replication.slave.offset.count', set => {
key_values => [ { name => 'slave_repl_offset' } ],
output_template => 'slave replication offset: %s s',
perfdatas => [
{ template => '%s', min => 0 }
]
}
},
{ label => 'slave-priority', nlabel => 'replication.slave.priority.count', set => {
key_values => [ { name => 'slave_priority' } ],
output_template => 'slave replication priority: %s',
perfdatas => [
{ template => '%s' }
]
}
},
{ label => 'slave-read-only', nlabel => 'replication.slave.readonly.count',set => {
key_values => [ { name => 'slave_read_only' } ],
output_template => 'slave readonly: %s',
perfdatas => [
{ template => '%s' }
]
}
}
];
}
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options, force_new_perfdata => 1);
bless $self, $class;
$options{options}->add_options(arguments => {});
return $self;
}
my %map_sync = (
0 => 'stopped',
1 => 'in progress'
);
my %map_cluster_state = (
0 => 'disabled',
1 => 'enabled'
);
sub manage_selection {
my ($self, %options) = @_;
my $results = $options{custom}->get_info();
$self->{global} = {
connected_slaves => $results->{connected_slaves},
role => $results->{role},
cluster_state => defined($results->{cluster_enabled}) ? $map_cluster_state{$results->{cluster_enabled}} : '-',
link_status => defined($results->{master_link_status}) ? $results->{master_link_status} : '-',
sync_status => defined($results->{master_sync_in_progress}) ? $map_sync{$results->{master_sync_in_progress}} : '-'
};
$self->{master} = { master_repl_offset => $results->{master_repl_offset} };
$self->{slave} = {
master_last_io_seconds_ago => $results->{master_last_io_seconds_ago},
slave_repl_offset => $results->{slave_repl_offset},
slave_priority => $results->{slave_priority},
slave_read_only => $results->{slave_read_only}
};
}
1;
__END__
=head1 MODE
Check replication status.
=over 8
=item B<--warning-status>
Set warning threshold for status (Default: '%{sync_status} =~ /in progress/i').
Can used special variables like: %{sync_status}, %{link_status}, %{cluster_state}
=item B<--critical-status>
Set critical threshold for status (Default: '%{link_status} =~ /down/i').
Can used special variables like: %{sync_status}, %{link_status}, %{cluster_state}
=item B<--warning-*>
Threshold warning.
Can be: 'connected-slaves', 'master-repl-offset',
'master-last-io', 'slave-priority', 'slave-read-only'.
=item B<--critical-*>
Threshold critical.
Can be: 'connected-slaves', 'master-repl-offset',
'master-last-io', 'slave-priority', 'slave-read-only'.
=back
=cut
| centreon/centreon-plugins | database/redis/mode/replication.pm | Perl | apache-2.0 | 6,673 |
#
# Copyright 2018 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package network::dlink::standard::snmp::mode::components::temperature;
use strict;
use warnings;
# In MIB 'env_mib.mib'
my $mapping = {
swTemperatureCurrent => { oid => '.1.3.6.1.4.1.171.12.11.1.8.1.2' },
};
my $oid_swTemperatureEntry = '.1.3.6.1.4.1.171.12.11.1.8.1';
sub load {
my ($self) = @_;
push @{$self->{request}}, { oid => $oid_swTemperatureEntry };
}
sub check {
my ($self) = @_;
$self->{output}->output_add(long_msg => "Checking temperatures");
$self->{components}->{temperature} = {name => 'temperatures', total => 0, skip => 0};
return if ($self->check_filter(section => 'temperature'));
foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{results}->{$oid_swTemperatureEntry}})) {
next if ($oid !~ /^$mapping->{swTemperatureCurrent}->{oid}\.(.*)$/);
my $instance = $1;
my $result = $self->{snmp}->map_instance(mapping => $mapping, results => $self->{results}->{$oid_swTemperatureEntry}, instance => $instance);
next if ($self->check_filter(section => 'temperature', instance => $instance));
$self->{components}->{temperature}->{total}++;
$self->{output}->output_add(long_msg => sprintf("Temperature '%s' is %dC.",
$instance, $result->{swTemperatureCurrent}));
my ($exit, $warn, $crit, $checked) = $self->get_severity_numeric(section => 'temperature', instance => $instance, value => $result->{swTemperatureCurrent});
if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) {
$self->{output}->output_add(severity => $exit,
short_msg => sprintf("Temperature '%s' is %s degree centigrade", $instance, $result->{swTemperatureCurrent}));
}
$self->{output}->perfdata_add(label => "temp_" . $instance, unit => 'C',
value => $result->{swTemperatureCurrent},
warning => $warn,
critical => $crit);
}
}
1; | wilfriedcomte/centreon-plugins | network/dlink/standard/snmp/mode/components/temperature.pm | Perl | apache-2.0 | 2,858 |
#!/usr/bin/perl
#use strict;
# checar somente os de hj
# qdo ainda esta rodando, tempo estimado fica negativo e loko
# DURACAO DO BACKUP: 3/4 do tempo eh conexao, e o resto eh disco
#minuto de inicio de cada backup
#$rmh{counter}{cr}{timer}='01';
#$rmh{counter}{eiserver}{timer}='12';
#$rmh{counter}{entidadejovem}{timer}='53';
#$rmh{counter}{donattiautomacao}{timer}='31';
#$rmh{counter}{donattiiluminacao}{timer}='06';
#$rmh{counter}{donattihidraulico}{timer}='38';
my $logfile;
my %rmh;
my $total;
my $read;
my $time;
$total='0';
$logfile='/home/alaska/usr/var/log/rsyncd.log';
############################### SUBS ################################
do("funcoes");
####################################################################
open(LOG, $logfile);
while (<LOG>) {
my @line;my @bug;
####2005/03/09 15:06:01 [27204] max connections (3) reached
#2005/03/01 08:06:02 [5987] rsync to donattiiluminacao/ from donattiiluminacao@201-1-142-238.dsl.telesp.net.br (201.1.142.238)
# BLINK IN THIS CASE
###2005/02/21 08:06:02 [8248] auth failed on module donattiiluminacao from 201-1-139-127.dsl.telesp.net.br (201.1.139.127)
@line=split(" ", $_);
$line[2]=~s/\[//g;
$line[2]=~s/\]//g;
if (/rsync\ to/) {
$total=$total+1;
chop $line[8];
$line[5]=~s/\///g;
$rmh{$line[2]}{nomeb}="$line[5]";
$rmh{$line[2]}{timestart}="$line[1]";
$rmh{$line[2]}{from}="$line[8]";
$rmh{$line[2]}{from}=~s/\(//g;
$rmh{counter}{$line[5]}='0' if (not defined $rmh{counter}{$line[5]});
$rmh{pids}{$line[5]}='' if (not defined $rmh{pids}{$line[5]});
# print "ANT $line[5]: $rmh{counter}{$line[5]}\n";
$rmh{counter}{$line[5]}=$rmh{counter}{$line[5]}+1;
# print "DEP $line[5]: $rmh{counter}{$line[5]}\n";
$rmh{pids}{$line[5]}="$rmh{pids}{$line[5]}"."$line[2] ";
}
#2005/03/01 11:06:04 [5987] wrote 69 bytes read 18676 bytes total size 111089708
#2005/03/03 04:14:18 [15314] rsync error: timeout in data send/receive (code 30) at io.c(153)
if ((/\]\ wrote\ /) || (/\]\ rsync\ error\:\ timeout\ in/)) {
# lets correct the time bug in rsyncd log
@bug=split(/\:/, $line[1]);
$rmh{$line[2]}{timeend}=($bug[0]-3)."\:$bug[1]\:$bug[2]";
$rmh{$line[2]}{size}=int($line[7]/1024) if ($line[7] =~ /[0-9]/);
$rmh{size}{$rmh{$line[2]}{nomeb}}='0' if (not defined $rmh{size}{$rmh{$line[2]}{nomeb}});
$rmh{size}{$rmh{$line[2]}{nomeb}}=$rmh{size}{$rmh{$line[2]}{nomeb}}+$rmh{$line[2]}{size};
# bug - a little reconect after a backup, was incrisin pids
# Not bugged, the second conection is other dir to backup
# if ((($line[4] == '69') && ($line[7] == '807')) || ($rmh{$line[2]}{timeend} =~ /$rmh{$line[2]}{timestart}/)) {
# $rmh{counter}{$rmh{$line[2]}{nomeb}}=$rmh{counter}{$rmh{$line[2]}{nomeb}}-1;
# $total=$total-1;
# undef $rmh{$line[2]};
# }
}
} # while
close(LOG);
print "Total: $total\n";
foreach (keys %{$rmh{counter}}) {
my @pids;my $pids;my $tmp;
$time='0';
print "Contei: $rmh{counter}{$_} para $_\n";
@pids=split(/\ /, $rmh{pids}{$_});
print " ";
foreach $pids (@pids) {
if (defined $rmh{$pids}) {
print "$pids " if (defined $rmh{$pids});
$time=$time+&timeconvert("$rmh{$pids}{timestart}", "$rmh{$pids}{timeend}");
}
}
print "\n";
$rmh{size}{$_}='0' if ( not defined $rmh{size}{$_});
print " Total bandwidth: $rmh{size}{$_} Kbytes\n";
print " Total time: ".&timeconvert2($time)."\n";
$tmp=&timeconvert2($time/$rmh{counter}{$_});
print " Tempo medio: ".&timeconvert2($tmp)."\n";
}
print "\nWhat pid you wanna know?\n";
$read=<STDIN>;chop $read;
$read='' if (not defined $read);
foreach (keys %{$rmh{$read}}) {
print "$_\: $rmh{$read}{$_}\n";
}
print "Backup is still runing\n" if ( not defined $rmh{$read}{timeend});
| drecchia/sri | RsyncdMonHelper-0.3/log.pl | Perl | apache-2.0 | 3,685 |
package Paws::ServiceCatalog::ScanProvisionedProducts;
use Moose;
has AcceptLanguage => (is => 'ro', isa => 'Str');
has AccessLevelFilter => (is => 'ro', isa => 'Paws::ServiceCatalog::AccessLevelFilter');
has PageSize => (is => 'ro', isa => 'Int');
has PageToken => (is => 'ro', isa => 'Str');
use MooseX::ClassAttribute;
class_has _api_call => (isa => 'Str', is => 'ro', default => 'ScanProvisionedProducts');
class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::ServiceCatalog::ScanProvisionedProductsOutput');
class_has _result_key => (isa => 'Str', is => 'ro');
1;
### main pod documentation begin ###
=head1 NAME
Paws::ServiceCatalog::ScanProvisionedProducts - Arguments for method ScanProvisionedProducts on Paws::ServiceCatalog
=head1 DESCRIPTION
This class represents the parameters used for calling the method ScanProvisionedProducts on the
AWS Service Catalog service. Use the attributes of this class
as arguments to method ScanProvisionedProducts.
You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to ScanProvisionedProducts.
As an example:
$service_obj->ScanProvisionedProducts(Att1 => $value1, Att2 => $value2, ...);
Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object.
=head1 ATTRIBUTES
=head2 AcceptLanguage => Str
The language code.
=over
=item *
C<en> - English (default)
=item *
C<jp> - Japanese
=item *
C<zh> - Chinese
=back
=head2 AccessLevelFilter => L<Paws::ServiceCatalog::AccessLevelFilter>
The access level for obtaining results. If left unspecified, C<User>
level access is used.
=head2 PageSize => Int
The maximum number of items to return in the results. If more results
exist than fit in the specified C<PageSize>, the value of
C<NextPageToken> in the response is non-null.
=head2 PageToken => Str
The page token of the first page retrieved. If null, this retrieves the
first page of size C<PageSize>.
=head1 SEE ALSO
This class forms part of L<Paws>, documenting arguments for method ScanProvisionedProducts in L<Paws::ServiceCatalog>
=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/ServiceCatalog/ScanProvisionedProducts.pm | Perl | apache-2.0 | 2,473 |
#
# Copyright 2021 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package apps::vmware::connector::mode::discovery;
use base qw(centreon::plugins::mode);
use strict;
use warnings;
use JSON::XS;
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$options{options}->add_options(arguments => {
'resource-type:s' => { name => 'resource_type' },
'prettify' => { name => 'prettify' }
});
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::init(%options);
}
sub run {
my ($self, %options) = @_;
my $response = $options{custom}->execute(params => $self->{option_results},
command => 'discovery', force_response => 1);
my $encoded_data;
eval {
if (defined($self->{option_results}->{prettify})) {
$encoded_data = JSON::XS->new->utf8->pretty->encode($response->{data});
} else {
$encoded_data = JSON::XS->new->utf8->encode($response->{data});
}
};
if ($@) {
$encoded_data = '{"code":"encode_error","message":"Cannot encode discovered data into JSON format"}';
}
$self->{output}->output_add(short_msg => $encoded_data);
$self->{output}->display(nolabel => 1, force_ignore_perfdata => 1);
}
1;
__END__
=head1 MODE
Resources discovery.
=over 8
=item B<--resource-type>
Choose the type of resources
to discover (Can be: 'esx', 'vm') (Mandatory).
=item B<--prettify>
Prettify JSON output.
=back
=cut
| Tpo76/centreon-plugins | apps/vmware/connector/mode/discovery.pm | Perl | apache-2.0 | 2,261 |
#!/usr/bin/perl
use strict;
use warnings;
#checar argumento
my $param = $ARGV[0];
unless (defined $param ) { print "Insira o caminho do arquivo a ser lido\n"; exit };
unless (-e $param) { print "Não consigo ler o arquivo $param\n"; exit ;}
#####################nao faz nada ainda
my @d=() ;
my @total25=();
my $arquivo = shift;
my @array;
my $elemento=0;
my $aa;
my $ab;
my $count;
# if ($arquivo =~ /^([-\@\w.]+)$/) { $arquivo = $1; }
# else{die "arquivo contem caracteres proibidos" ;}
open(my $fh, '<:encoding(UTF-8)', $arquivo)
or die "Não foi possível abrir o arquivo '$arquivo' $!";
chomp(@array = <$fh>);
#
# while( my $linha = <$fh>) {
# print $linha;
# # last if $. == 2;
# }
close $fh;
s/#0/ /g for @array;
s/#/ /g for @array;
s/0([0-9])/$1/g for @array;
#inicializa o vetor resposta
foreach my $i (0..24) { $total25[$i]=0; }
foreach $aa (@array) {
@d=split(' ',$aa);
$count=0;
foreach $elemento (@d) {
$total25[$elemento]++;
$count ++ ;
}
# print "=================\n";
}
$count=1;
shift @total25 ;
foreach $ab (@total25) { print "$count $ab\n" ; $count++} | jmhenrique/bla | lota.pl | Perl | apache-2.0 | 1,169 |
# Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
# Copyright [2016-2022] EMBL-European Bioinformatics Institute
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
use strict;
use warnings;
# Transform a Compara resource class into a category name according to the
# memory requirement.
sub get_key_name {
my $resource_class = shift;
my $display_name = $resource_class->display_name;
my $memory_req = $display_name;
# Convert special names to the standard nomenclature
$memory_req = '250Mb_job' if $display_name eq 'default';
$memory_req = '250Mb_job' if $display_name eq 'urgent';
$memory_req = '2Gb_job' if $display_name eq 'msa';
$memory_req = '8Gb_job' if $display_name eq 'msa_himem';
# Remove stuff we don't need
$memory_req =~ s/_(job|mpi|big_tmp)//g;
$memory_req =~ s/_\d+(_hour|min|c$)//g;
# Convert to GBs
$memory_req =~ s/Gb$//;
if ($memory_req =~ /^(\d+)Mb$/) {
$memory_req = $1/1000;
} elsif ($memory_req =~ /^mem(\d+)$/) {
$memory_req = $1/1000;
}
if ($memory_req < 1) {
return '<1';
} elsif ($memory_req <= 4) {
return '1-4';
} elsif ($memory_req <= 8) {
return '5-8';
} elsif ($memory_req <= 16) {
return '9-16';
} elsif ($memory_req <= 32) {
return '17-32';
} elsif ($memory_req <= 128) {
return '33-128';
} else {
return 'bigmem';
}
}
=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 subscribe to the eHive mailing list: http://listserver.ebi.ac.uk/mailman/listinfo/ehive-users to discuss eHive-related questions or to be notified of our updates
=cut
1;
| Ensembl/ensembl-hive | scripts/dev/generate_timeline_example_key_transform_file.pl | Perl | apache-2.0 | 2,880 |
=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::Runnable::Sam2Bam
=head1 SYNOPSIS
my $runnable =
Bio::EnsEMBL::Analysis::Runnable::Sam2Bam->new();
$runnable->run;
my @results = $runnable->output;
=head1 DESCRIPTION
This module uses samtools to convert a directory containing SAM
files into a single sorted indexed merged BAM file
=head1 METHODS
=cut
package Bio::EnsEMBL::Analysis::Runnable::Sam2Bam;
use warnings ;
use strict;
use File::Copy qw(mv);
use Bio::EnsEMBL::Utils::Exception qw(throw warning);
use Bio::EnsEMBL::Utils::Argument qw( rearrange );
use Bio::EnsEMBL::Analysis::Runnable::Samtools;
use parent ('Bio::EnsEMBL::Analysis::Runnable');
=head2 new
Arg [HEADER] : String
Arg [SAMFILES]: String
Arg [BAMFILE] : String
Arg [GENOME] : String
Description : Creates a new Bio::EnsEMBL::Analysis::Runnable::Sam2Bam object to convert SAM files
to a BAM file
Returntype : Bio::EnsEMBL::Analysis::Runnable::Sam2Bam
Exceptions : Throws if you have no files to work on
Throws if BAMFILE or GENOME is not set
=cut
sub new {
my ( $class, @args ) = @_;
my $self = $class->SUPER::new(@args);
my ($header, $samfiles, $bamfile, $genome, $use_threads) = rearrange([qw(HEADER SAMFILES BAMFILE GENOME USE_THREADING)],@args);
$self->throw("You have no files to work on\n") unless (scalar(@$samfiles));
$self->samfiles($samfiles);
$self->headerfile($header);
$self->throw("You must define an output file\n") unless $bamfile;
$self->bamfile($bamfile);
$self->throw("You must define a genome file\n") unless $genome;
$self->genome($genome);
$self->use_threads($use_threads);
return $self;
}
=head2 run
Args : none
Description: Merges Sam files defined in the config using Samtools
Returntype : none
=cut
sub run {
my ($self) = @_;
# get a list of files to use
my $bamfile = $self->bamfile;
my $program = $self->program;
my $samtools = Bio::EnsEMBL::Analysis::Runnable::Samtools->new(
-program => $program,
-use_threading => $self->use_threads,
);
my $count = 0;
my @fails;
# next make all the sam files into one big sam flie
open (BAM ,">$bamfile.sam" ) or $self->throw("Cannot open sam file for merging $bamfile.sam");
if ($self->headerfile and $samtools->version) {
open(HH, $self->headerfile) || $self->throw('Could not open header file for reading');
while(<HH>) {
print BAM $_;
}
close(HH) || $self->throw('Could not close header file after reading');
}
my @sam = @{$self->samfiles};
foreach my $file ( @{$self->samfiles} ) {
my $line;
open ( SAM ,"$file") or $self->throw("Cannot open file '$file'\n");
my $line_count = 0;
while (<SAM>) {
if ($_ =~ /^\@\w+/) {
$line = $_;
}
else {
chomp;
print BAM $_, "\n";
$line_count++;
}
}
close(SAM) || $self->throw("Failed closing '$file'");
$count++;
push @fails,$file unless ( $line eq '@EOF' or $line_count == 0 );
}
close(BAM) || $self->throw("Failed closing sam file for merging $bamfile.sam");
print "Merged $count files\n";
if ( scalar(@fails) > 0 ) {
$self->throw(join("\n", 'The following sam files failed to complete, you need to run them again', @fails));
}
# now call sam tools to do the conversion.
# is the genome file indexed?
# might want to check if it's already indexed first
if (!-e $self->genome.'.fai') {
$samtools->index_genome($self->genome);
}
$samtools->run_command('view', '-b -h -S -T '.$self->genome, $bamfile.'_unsorted.bam', "$bamfile.sam");
# add readgroup info if there is any
if ($self->headerfile and !$samtools->version) {
# dump out the sequence header
$samtools->run_command('view', '-H', "$bamfile.header", $bamfile.'_unsorted.bam');
open(FH, $self->headerfile) || throw('Could not open '.$self->headerfile);
open(WH, '>>', "$bamfile.header") || throw("Could not open $bamfile.header for appending");
while(<FH>) {
print WH $_;
}
close(WH) || throw("Could not close $bamfile.header for appending");
close(FH) || throw('Could not close '.$self->headerfile);
$samtools->reheader("$bamfile.header", $bamfile.'_unsorted.bam', "$bamfile.fixed_header.bam");
mv("$bamfile.fixed_header.bam", "$bamfile"."_unsorted.bam");
}
$samtools->sort($bamfile, $bamfile.'_unsorted.bam');
$samtools->index($bamfile.'.bam');
$self->files_to_delete($bamfile.'_unsorted.bam');
$self->delete_files();
}
#Containers
#=================================================================
=head2 headerfile
Arg [1] : (optional) String
Description: Getter/setter
Returntype : String
Exceptions : Throws if file doesn't exist
=cut
sub headerfile {
my ($self,$value) = @_;
if (defined $value) {
$self->throw("Cannot find read group header file $value\n")
unless (-e $value);
$self->{'_headerfile'} = $value;
}
if (exists($self->{'_headerfile'})) {
return $self->{'_headerfile'};
} else {
return;
}
}
=head2 samfiles
Arg [1] : (optional) Arrayref of String
Description: Getter/setter
Returntype : Arrayref of String
Exceptions : None
=cut
sub samfiles {
my ($self,$value) = @_;
if (defined $value) {
$self->{'_samfiles'} = $value;
}
if (exists($self->{'_samfiles'})) {
return $self->{'_samfiles'};
} else {
return;
}
}
=head2 bamfile
Arg [1] : (optional) String
Description: Getter/setter
Returntype : String
Exceptions : None
=cut
sub bamfile {
my ($self,$value) = @_;
if (defined $value) {
$self->{'_bamfile'} = $value;
}
if (exists($self->{'_bamfile'})) {
return $self->{'_bamfile'};
} else {
return;
}
}
=head2 genome
Arg [1] : (optional) String
Description: Getter/setter
Returntype : String
Exceptions : Throws if the file doesn't exists
=cut
sub genome {
my ($self,$value) = @_;
if (defined $value) {
$self->throw($value.' does not exist!') unless (-e $value);
$self->{'_genome'} = $value;
}
if (exists($self->{'_genome'})) {
return $self->{'_genome'};
} else {
return;
}
}
=head2 use_threads
Arg [1] : (optional) Int
Description: Getter/setter
Returntype : Int
Exceptions : None
=cut
sub use_threads {
my ($self, $value) = @_;
if (defined $value) {
$self->{'_use_threads'} = $value;
}
if (exists($self->{'_use_threads'})) {
return $self->{'_use_threads'};
} else {
return;
}
}
1;
| Ensembl/ensembl-analysis | modules/Bio/EnsEMBL/Analysis/Runnable/Sam2Bam.pm | Perl | apache-2.0 | 7,562 |
#
# Copyright 2016 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package centreon::common::fastpath::mode::memory;
use base qw(centreon::plugins::mode);
use strict;
use warnings;
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$self->{version} = '1.0';
$options{options}->add_options(arguments =>
{
"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) = @_;
$self->{snmp} = $options{snmp};
my $oid_agentSwitchCpuProcessMemFree = '.1.3.6.1.4.1.674.10895.5000.2.6132.1.1.1.1.4.1.0'; # in KB
my $oid_agentSwitchCpuProcessMemAvailable = '.1.3.6.1.4.1.674.10895.5000.2.6132.1.1.1.1.4.2.0'; # in KB
my $result = $self->{snmp}->get_leef(oids => [$oid_agentSwitchCpuProcessMemFree,
$oid_agentSwitchCpuProcessMemAvailable],
nothing_quit => 1);
my $memory_free = $result->{$oid_agentSwitchCpuProcessMemFree} * 1024;
my $memory_available = $result->{$oid_agentSwitchCpuProcessMemAvailable} * 1024;
my $memory_used = $memory_available - $memory_free;
my $prct_used = ($memory_used / $memory_available) * 100;
my $prct_free = ($memory_free / $memory_available) * 100;
my $exit = $self->{perfdata}->threshold_check(value => $prct_used, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]);
my ($memory_used_value, $memory_used_unit) = $self->{perfdata}->change_bytes(value => $memory_used);
my ($memory_available_value, $memory_available_unit) = $self->{perfdata}->change_bytes(value => $memory_available);
my ($memory_free_value, $memory_free_unit) = $self->{perfdata}->change_bytes(value => $memory_free);
$self->{output}->output_add(severity => $exit,
short_msg => sprintf("Memory used: %s (%.2f%%), Size: %s, Free: %s (%.2f%%)",
$memory_used_value . " " . $memory_used_unit, $prct_used,
$memory_available_value . " " . $memory_available_unit,
$memory_free_value . " " . $memory_free_unit, $prct_free));
$self->{output}->perfdata_add(label => "used", unit => 'B',
value => $memory_used,
warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning', total => $memory_available, cast_int => 1),
critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical', total => $memory_available, cast_int => 1),
min => 0, max => $memory_available);
$self->{output}->display();
$self->{output}->exit();
}
1;
__END__
=head1 MODE
Check memory usage (FASTPATH-SWITCHING-MIB).
=over 8
=item B<--warning>
Threshold warning in percent.
=item B<--critical>
Threshold critical in percent.
=back
=cut
| bcournaud/centreon-plugins | centreon/common/fastpath/mode/memory.pm | Perl | apache-2.0 | 4,589 |
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2017] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
=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
# Ensembl module for Bio::EnsEMBL::Variation::SampleGenotype
#
#
=head1 NAME
Bio::EnsEMBL::Variation::SampleGenotype-Module representing the genotype
of a single sample at a single position
=head1 SYNOPSIS
print $genotype->variation()->name(), "\n";
print $genotype->allele1(), '/', $genotype->allele2(), "\n";
print $genotype->sample()->name(), "\n";
=head1 DESCRIPTION
This is a class representing the genotype of a single diploid sample at
a specific position
=head1 METHODS
=cut
use strict;
use warnings;
package Bio::EnsEMBL::Variation::SampleGenotype;
use Bio::EnsEMBL::Variation::Genotype;
use Bio::EnsEMBL::Utils::Argument qw(rearrange);
use Bio::EnsEMBL::Utils::Exception qw(throw warning);
use vars qw(@ISA);
@ISA = qw(Bio::EnsEMBL::Variation::Genotype);
=head2 new
Arg [-adaptor] :
Bio::EnsEMBL::Variation::DBSQL::SampleGenotypeAdaptor
Arg [-genotype] :
arrayref - arrayref of alleles making up this genotype (in haplotype order)
Arg [-allele2] :
string - One of the two alleles defining this genotype
Arg [-variation] :
Bio::EnsEMBL::Variation::Variation - The variation associated with this
genotype
Arg [-sample] :
Bio::EnsEMBL::Variation::Sample - The sample this genotype is for.
Example : $sample_genotype = Bio:EnsEMBL::Variation::SampleGenotype->new(
-start => 100,
-end => 100,
-strand => 1,
-slice => $slice,
-genotype => ['A','T'],
-variation => $variation,
-sample => $sample
);
Description: Constructor. Instantiates a SampleGenotype object.
Returntype : Bio::EnsEMBL::Variation::SampleGenotype
Exceptions : throw on bad argument
Caller : general
Status : Stable
=cut
sub new {
my $caller = shift;
my $class = ref($caller) || $caller;
my $self = $class->SUPER::new(@_);
my ($adaptor, $genotype, $var, $varid, $ssid, $sample, $phased) =
rearrange([qw(adaptor genotype variation _variation_id subsnp sample phased)],@_);
if(defined($var) && (!ref($var) || !$var->isa('Bio::EnsEMBL::Variation::Variation'))) {
throw("Bio::EnsEMBL::Variation::Variation argument expected");
}
if(defined($sample) && (!ref($sample) || !$sample->isa('Bio::EnsEMBL::Variation::Sample'))) {
throw("Bio::EnsEMBL::Variation::Sample argument expected");
}
$self->{'adaptor'} = $adaptor;
$self->{'genotype'} = $genotype;
$self->{'sample'} = $sample;
$self->{'variation'} = $var;
$self->{'subsnp'} = $ssid;
$self->{'phased'} = $phased;
$self->{'_variation_id'} = $varid unless defined $var;
return $self;
}
=head2 sample
Arg [1] : (optional) Bio::EnsEMBL::Variation::Sample $ind
Example : $sample = $sample_genotype->sample();
Description: Getter/Setter for the sample associated with this genotype
Returntype : Bio::EnsEMBL::Variation::Sample
Exceptions : throw on bad argument
Caller : general
Status : Stable
=cut
sub sample {
my $self = shift;
if (@_) {
my $sample = shift;
if (defined($sample) && (!ref($sample) || !$sample->isa('Bio::EnsEMBL::Variation::Sample'))) {
throw('Bio::EnsEMBL::Variation::Sample argument expected');
}
return $self->{'sample'} = $sample;
}
if (!defined($self->{sample}) && defined($self->{sample_id})) {
my $sa = $self->adaptor->db->get_SampleAdaptor;
if (defined($sa)) {
my $sample = $sa->fetch_by_dbID($self->{sample_id});
if (defined($sample)) {
$self->{sample} = $sample;
delete $self->{sample_id};
}
}
}
return $self->{'sample'};
}
1;
| willmclaren/ensembl-variation | modules/Bio/EnsEMBL/Variation/SampleGenotype.pm | Perl | apache-2.0 | 4,573 |
#!/usr/bin/perl
#
# $Id:$
#
# perl test driver
use Atrshmlog;
$result = Atrshmlog::attach();
$s = shift @ARGV;
$val = Atrshmlog::get_env($s);
print "get env : $val : \n";
$val = Atrshmlog::get_env_shmid();
print "get env : $val : \n";
$val = Atrshmlog::get_env_id_suffix();
print "get env : $val : \n";
print " \n";
exit (0);
# end of main
| atrsoftgmbh/atrshmlog | perl/src/tests/t_get_env.pl | Perl | apache-2.0 | 353 |
package
TestSchema::Result::SkipEnd;
our $VERSION = '0.11';
use base 'DBIx::Class';
__PACKAGE__->load_components(qw(Core));
__PACKAGE__->table('skip_end');
__PACKAGE__->add_columns(
id => { data_type => 'integer' },
name => { data_type => 'character varying' },
password => { data_type => 'character varying' },
);
__PACKAGE__->set_primary_key('id');
1; | kforner/CatalystX-ExtJS | t/lib/TestSchema/Result/SkipEnd.pm | Perl | bsd-3-clause | 379 |
#
# Mail::SPF::v1::Record
# SPFv1 record class.
#
# (C) 2005-2008 Julian Mehnle <julian@mehnle.net>
# 2005 Shevek <cpan@anarres.org>
# $Id: Record.pm 50 2008-08-17 21:28:15Z Julian Mehnle $
#
##############################################################################
package Mail::SPF::v1::Record;
=head1 NAME
Mail::SPF::v1::Record - SPFv1 record class
=cut
use warnings;
use strict;
use base 'Mail::SPF::Record';
use constant TRUE => (0 == 0);
use constant FALSE => not TRUE;
use constant mech_classes => {
all => 'Mail::SPF::Mech::All',
ip4 => 'Mail::SPF::Mech::IP4',
ip6 => 'Mail::SPF::Mech::IP6',
a => 'Mail::SPF::Mech::A',
mx => 'Mail::SPF::Mech::MX',
ptr => 'Mail::SPF::Mech::PTR',
'exists' => 'Mail::SPF::Mech::Exists',
include => 'Mail::SPF::Mech::Include'
};
use constant mod_classes => {
redirect => 'Mail::SPF::Mod::Redirect',
'exp' => 'Mail::SPF::Mod::Exp'
};
eval("require $_")
foreach values(%{mech_classes()}), values(%{mod_classes()});
use constant version_tag => 'v=spf1';
use constant version_tag_pattern => qr/ v=spf(1) (?= \x20 | $ ) /ix;
use constant scopes => ('helo', 'mfrom');
=head1 SYNOPSIS
See L<Mail::SPF::Record>.
=head1 DESCRIPTION
An object of class B<Mail::SPF::v1::Record> represents an B<SPFv1> (C<v=spf1>)
record.
=head2 Constructors
The following constructors are provided:
=over
=item B<new(%options)>: returns I<Mail::SPF::v1::Record>
Creates a new SPFv1 record object.
%options is a list of key/value pairs representing any of the following
options:
=over
=item B<text>
=item B<terms>
=item B<global_mods>
See L<Mail::SPF::Record/new>.
=item B<scopes>
See L<Mail::SPF::Record/new>. Since SPFv1 records always implicitly cover the
C<helo> and C<mfrom> scopes, this option must either be exactly B<['helo',
'mfrom']> (or B<['mfrom', 'helo']>) or be omitted.
=back
=cut
sub new {
my ($self, %options) = @_;
$self = $self->SUPER::new(%options);
if (defined(my $scopes = $self->{scopes})) {
@$scopes > 0
or throw Mail::SPF::EInvalidScope('No scopes for v=spf1 record');
@$scopes == 2 and
(
$scopes->[0] eq 'help' and $scopes->[1] eq 'mfrom' or
$scopes->[0] eq 'mfrom' and $scopes->[1] eq 'help'
)
or throw Mail::SPF::EInvalidScope(
"Invalid set of scopes " . join(', ', map("'$_'", @$scopes)) . " for v=spf1 record");
}
return $self;
}
=item B<new_from_string($text, %options)>: returns I<Mail::SPF::v1::Record>;
throws I<Mail::SPF::ENothingToParse>, I<Mail::SPF::EInvalidRecordVersion>,
I<Mail::SPF::ESyntaxError>
Creates a new SPFv1 record object by parsing the string and any options given.
=back
=head2 Class methods
The following class methods are provided:
=over
=item B<version_tag_pattern>: returns I<Regexp>
Returns a regular expression that matches a version tag of B<'v=spf1'>.
=item B<default_qualifier>
=item B<results_by_qualifier>
See L<Mail::SPF::Record/Class methods>.
=back
=head2 Instance methods
The following instance methods are provided:
=over
=item B<text>
=item B<scopes>
=item B<terms>
=item B<global_mods>
=item B<global_mod>
=item B<stringify>
=item B<eval>
See L<Mail::SPF::Record/Instance methods>.
=item B<version_tag>: returns I<string>
Returns B<'v=spf1'>.
=back
=head1 SEE ALSO
L<Mail::SPF>, L<Mail::SPF::Record>, L<Mail::SPF::Term>, L<Mail::SPF::Mech>,
L<Mail::SPF::Mod>
L<http://www.ietf.org/rfc/rfc4408.txt>
For availability, support, and license information, see the README file
included with Mail::SPF.
=head1 AUTHORS
Julian Mehnle <julian@mehnle.net>, Shevek <cpan@anarres.org>
=cut
TRUE;
| memememomo/Mail-SPF | lib/Mail/SPF/v1/Record.pm | Perl | bsd-3-clause | 3,814 |
#!/usr/bin/perl -w
#### DEBUG
my $DEBUG = 0;
#$DEBUG = 1;
#### TIME
my $time = time();
my $duration = 0;
my $current_time = $time;
=head2
APPLICATION bamToJbrowse
PURPOSE
GENERATE JBROWSE JSON FEATURES FROM REMOTE BAM FILE
INPUT
OUTPUT
NOTES
Bio::DB::Bam::Alignment -- The SAM/BAM alignment object
use Bio::DB::Sam;
my $sam = Bio::DB::Sam->new(-fasta=>"data/ex1.fa",
-bam =>"data/ex1.bam");
my @alignments = $sam->get_features_by_location(-seq_id => 'seq2',
-start => 500,
-end => 800);
for my $a (@alignments)
{
my $seqid = $a->seq_id;
my $start = $a->start;
my $end = $a->end;
my $strand = $a->strand;
my $ref_dna= $a->dna;
my $query_start = $a->query->start;
my $query_end = $a->query->end;
my $query_strand = $a->query->strand;
my $query_dna = $a->query->dna;
my $cigar = $a->cigar_str;
my @scores = $a->qscore; # per-base quality scores
my $match_qual= $a->qual; # quality of the match
my $paired = $a->get_tag_values('PAIRED');
}
USAGE
./bamToJbrowse.pl <--inputfiles String> <--outputdir String>
<--inputdir String> [--splitfile String] [--reads Integer] [--convert]
[--clean] [--queue String] [--maxjobs Integer] [--cpus Integer] [--help]
--outputdir : Directory with one subdirectory per reference chromosome
containing an out.sam or out.bam alignment output file
--inputdir : Location of directory containing chr*.fa reference files
--chromodir : Name of the reference chromodir (e.g., 'mouse')
--queue : Cluster queue name
--cluster : Cluster type (LSF|PBS)
--help : print help info
EXAMPLES
/nethome/bioinfo/apps/agua/0.5/bin/apps/bamToJbrowse.pl \
--refseqfile /nethome/syoung/base/pipeline/jbrowse/ucsc/reference/refSeqs.js \
--outputdir /scratch/syoung/base/pipeline/jbrowse/agua/0.5/maq1 \
--inputdir /scratch/syoung/base/pipeline/SRA/NA18507/maq/maq1 \
--filetype bam \
--filename "out.bam" \
--label maq1 \
--key maq1 \
--queue large \
--cluster LSF
=cut
use strict;
#### EXTERNAL MODULES
use Term::ANSIColor qw(:constants);
use Data::Dumper;
use Getopt::Long;
use FindBin qw($Bin);
#### USE LIBRARY
use lib "$Bin/../../lib";
#### INTERNAL MODULES
use JBrowse;
use Timer;
use Util;
use Conf::Yaml;
##### STORE ARGUMENTS TO PRINT TO FILE LATER
my @arguments = @ARGV;
unshift @arguments, $0;
#### FLUSH BUFFER
$| =1;
#### SET JBrowse LOCATION
my $conf = Conf::Yaml->new(inputfile=>"$Bin/../../../conf/config.yaml");
my $jbrowse = $conf->getKey("data", 'JBROWSE');
print "JBROWSE: $jbrowse\n";
my $samtools = $conf->getKey("applications", 'SAMTOOLS');
#### DEFAULT MAX FILE LINES (MULTIPLE OF 4 BECAUSE EACH FASTQ RECORD IS 4 LINES)
my $maxlines = 4000000;
#### GET OPTIONS
my $outputdir;
my $inputdir;
my $filename;
my $filetype;
my $label;
my $key;
my $refseqfile;
#### CLUSTER OPTIONS
my $tempdir = "/tmp";
my $cluster = "PBS";
my $queue = "gsmall";
my $maxjobs = 30;
my $cpus = 1;
my $sleep = 5;
my $parallel;
my $verbose;
my $dot = 1;
my $help;
print "bamToJbrowse.pl Use option --help for usage instructions.\n" and exit if not GetOptions (
#### JBROWSE
'inputdir=s' => \$inputdir,
'outputdir=s' => \$outputdir,
'filename=s' => \$filename,
'filetype=s' => \$filetype,
'label=s' => \$label,
'key=s' => \$key,
'refseqfile=s' => \$refseqfile,
'jbrowse=s' => \$jbrowse,
#### CLUSTER
'maxjobs=i' => \$maxjobs,
'cpus=i' => \$cpus,
'cluster=s' => \$cluster,
'queue=s' => \$queue,
'sleep=i' => \$sleep,
'verbose' => \$verbose,
'tempdir=s' => \$tempdir,
'help' => \$help
);
#### PRINT HELP
if ( defined $help ) { usage(); }
#### CHECK INPUTS
die "outputdir not defined (Use --help for usage)\n" if not defined $outputdir;
die "inputdir not defined (Use --help for usage)\n" if not defined $inputdir;
die "filetype not defined (Use --help for usage)\n" if not defined $filetype;
die "filename not defined (Use --help for usage)\n" if not defined $filename;
die "label not defined (Use --help for usage)\n" if not defined $label;
die " not defined (Use --help for usage)\n" if not defined $key;
die "refseqfile not defined (Use --help for usage)\n" if not defined $refseqfile;
die "jbrowse not defined (Use --help for usage)\n" if not defined $jbrowse;
print "Can't find outputdir: $outputdir\n" if not -d $outputdir;
#### CHECK FILETYPE IS SUPPORTED
print "filetype not supported (bam|gff): $filetype\n" and exit if $filetype !~ /^(bam|gff)$/;
#### DEBUG
print "bamToJbrowse.pl outputdir: $outputdir\n";
print "bamToJbrowse.pl inputdir: $inputdir\n";
print "bamToJbrowse.pl filetype: $filetype\n";
print "bamToJbrowse.pl refseqfile: $refseqfile\n";
#### INSTANTIATE JBrowse OBJECT
my $jbrowseObject = JBrowse->new(
{
#### JBROWSE
inputdir => $inputdir,
outputdir => $outputdir,
refseqfile => $refseqfile,
filetype => $filetype,
filename => $filename,
label => $label,
key => $key,
jbrowse => $jbrowse,
#### CLUSTER
cluster => $cluster,
queue => $queue,
maxjobs => $maxjobs,
cpus => $cpus,
sleep => $sleep,
tempdir => $tempdir,
dot => $dot,
verbose => $verbose,
command => \@arguments
}
);
#### GENERATE FEATURES
$jbrowseObject->generateFeatures();
#### PRINT RUN TIME
my $runtime = Timer::runtime( $time, time() );
print "bamToJbrowse.pl Run time: $runtime\n";
print "bamToJbrowse.pl Completed $0\n";
print "bamToJbrowse.pl ";
print Timer::current_datetime(), "\n";
print "bamToJbrowse.pl ****************************************\n\n\n";
exit;
#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
# SUBROUTINES
#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub usage
{
print GREEN;
print `perldoc $0`;
print RESET;
exit;
}
| aguadev/aguadev | bin/jbrowse/bamToJbrowse.pl | Perl | mit | 6,066 |
/*
* Copyright (C) 2002, 2007 Christoph Wernhard
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see <http://www.gnu.org/licenses/>.
*/
:- module(task_plan, [plan_1/7]).
:- use_module(planner_run).
:- use_module(planner_convert).
:- use_module(obj_task).
:- use_module(obj_inverse).
:- use_module(solution_dotgraph).
:- use_module('swilib/err').
:- use_module('swilib/term_support').
:- use_module('swilib/pretty').
:- use_module(library(time)).
%
% SWI-BUG in library(time):
%
% 1 ?- call_with_time_limit(1, fail).
% ERROR: Arguments are not sufficiently instantiated
% 2 ?-
%
% SWI-BUG in library(time):
%
% - if code within time limit is exited due to another exception or break, the
% signal is not removed (i.e. some later unrelated call throws
% time_limit_exceeded)
%
% ?- call_with_time_limit(5, sleep(5)).
% [press ctrl-c, "a" for abort, wait 5 seconds]
% ?- true.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%
%%%% Utilities
%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
:- dynamic(atl/1).
% Notes: call_with_time_limit(+Seconds, :Goal)
% raises time_limit_exceeded
% Time seems to be real time in seconds, granularity system dependent, about
% 50 or 10 milliseconds
:- module_transparent call_limited/3.
:- module_transparent call_limited_solutions/2.
%%%%
%%%% Enumerate maximal NSols solutions obtained within time limit.
%%%%
call_limited(NSols, Time, Goal) :-
retractall(atl(_)),
catch( call_with_time_limit(Time,
once(( task_plan:call_limited_solutions(NSols, Goal),
assert(task_plan:atl(Goal)),
fail
; true))),
time_limit_exceeded,
true ),
retract(atl(Goal)).
call_limited_solutions(0, _) :-
!,
fail.
call_limited_solutions(NSols, Goal) :-
flag(task_plan_atl, _, 1),
call(Goal),
flag(task_plan_atl, N, N + 1),
( N < NSols ->
true
; !
).
%%%%
%%%% plan_1(+KB, +Task, +AT, -Solution)
%%%%
plan_1(KB, Timeout, Mode, Task, AT, KBOut, Solutions) :-
CsModule = planner_cs_simple,
task_goal(Task, Goal),
task_start(Task, Start),
task_input_constraints(Task, InCs),
task_rules(Task, Rules),
fluent_declarations_for_bodies(Rules, Decls),
append(Rules, Decls, Rules1),
% tmp_file('debug_planner.pl', OutFile),
% Options = [out(OutFile),
Options = [out(_),
p(Plan),pool(Pool),pxo,bd,o1,s1,cs_module(CsModule)],
( uses_constraints(Task) ->
Options1 = [cs(OutCs)|Options]
; OutCs = [],
Options1 = Options
),
% %% Debugging - print the planning task to stderr
% %%
% fromonto:onto_stream(( writeln('DEBUG: Planning task:'),
% pretty:pp(plan(Options1, Goal, Start, InCs, Rules1)),
% nl ),
% user_error),
Call = ( plan(Options1, Goal, Start, InCs, Rules1),
term_variables(t(Goal, Start, InCs, Plan, Pool),
SolutionVars),
CsModule:project_cs(OutCs, SolutionVars, OutCs1) ),
MaxNumOfRawSolutions = 50, %% *** to config
findall(Plan-raw_solution(Goal, Start, InCs, OutCs1, Pool),
( Mode = multi ->
call_limited(MaxNumOfRawSolutions, Timeout, Call)
; catch( call_with_time_limit(Timeout, once(Call)),
%% SWI 5.6.40 OS-X: explicit once seems
time_limit_exceeded,
fail )
),
RawPlanXs),
gensym('inf_result', KBId),
create_knowledgebase_like(KB, KBId, [], KBOut),
%% *** also put the infraengine schema to KBOut
prepare_solutions(KBOut, RawPlanXs, AT, Solutions).
prepare_solutions(KB, RawPlanXs, AT, Solutions) :-
length(RawPlanXs, LengthIn),
msg('Planning task: ~w raw plans.', [LengthIn]),
RawPlanXs1 = RawPlanXs,
% remove_subsumed_elements(RawPlanXs, RawPlanXs1),
% length(RawPlanXs1, LengthSPruned),
% msg('Planning task: Syntactically pruned to ~w plans.',
% [LengthSPruned]),
msg('Planning task: removing redundant plans.'),
prune_plans_by_nodeset_1(RawPlanXs1, GPlanXs),
length(GPlanXs, LengthPruned),
msg('Planning task: ~w plans remaining.',
[LengthPruned]),
inverse_access_templates(AT, TA),
map_prepare_solution(GPlanXs, KB, TA, Solutions).
map_prepare_solution([X|Xs], Y1, Y2, [X1|Xs1]) :-
prepare_solution(X, Y1, Y2, X1),
map_prepare_solution(Xs, Y1, Y2, Xs1).
map_prepare_solution([], _, _, []).
prepare_solution(Plan-RawSolution, KB, TA, Solution) :-
RawSolution = raw_solution(_Goal, _Start, _InCs, OutCs, _Pool),
gplan_to_obj(Plan, TA, ObjsPlan),
%% pool_to_obj(Pool, TA, ObjsPool), ***
prettify_constraints(OutCs, OutCs1),
%% VTerm = RawSolution, ***
VTerm = OutCs1,
plain_to_obj_fix_vars([ObjsPlan], VTerm, [ObjsPlan1]),
with_output_to(atom(OutCs2), pretty:pp(OutCs1)),
gplan_goal_node_id(Plan, GoalNode),
gensym('http://www.infraengine.com/id/id', Solution),
gensym('http://www.infraengine.com/id/id', ConstrItem),
RDFSol = [rdf(Solution, rdf_type, inf_Solution),
rdf(Solution, inf_solutionPlan, GoalNode),
rdf(Solution, inf_solutionConstraints, ConstrItem),
rdf(ConstrItem, inf_expression, literal(OutCs2))],
objs_to_rdf(ObjsPlan1, RDFPlan),
add_facts(KB, [inf_tmp, inf_tmp], [RDFSol, RDFPlan], [[]]).
prettify_constraints([atom_number(X, Y)|Cs], Cs1) :-
unify_with_occurs_check(X, Y),
!,
prettify_constraints(Cs, Cs1).
prettify_constraints([C|Cs], [C|Cs1]) :-
prettify_constraints(Cs, Cs1).
prettify_constraints([], []).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%
%%%% prune_plans_by_nodeset_1
%%%%
%%%% Follows the implementation of prune_plans_by_nodeset
%%%% in planner_convert, but allows to associate extra information with
%%%% the plans, that is just passed in and out.
%%%%
%%%% *** TODO: consider constraints and pool
%%%%
prune_plans_by_nodeset_1(RawPlansX, GPlansX) :-
map_plan_to_gplan_1(RawPlansX, G1),
prune_gplans_by_nodeset_1(G1, GPlansX).
prune_gplans_by_nodeset_1(GPlansX, GPlans1X) :-
red_subs_by_nodeset_1(GPlansX, G3),
map_gplan_minimize_1(G3, GPlans1X).
map_gplan_minimize_1([X-Y|Xs], [X1-Y|Xs1]) :-
gplan_minimize(X, X1),
map_gplan_minimize_1(Xs, Xs1).
map_gplan_minimize_1([], []).
map_plan_to_gplan_1([X-Y|Xs], [X1-Y|Xs1]) :-
plan_to_gplan(X, X1),
map_plan_to_gplan_1(Xs, Xs1).
map_plan_to_gplan_1([], []).
red_subs_by_nodeset_1(Gs, Gs1) :-
rs1_bn(Gs, [], Gs1).
rs1_bn([G-_|Gs], Gs1, Gs2) :-
( member(G1-_, Gs)
; member(G1, Gs1)
),
gplan_subsumes_chk_by_nodeset(G1, G),
!,
rs1_bn(Gs, Gs1, Gs2).
rs1_bn([G-X|Gs], Gs1, [G-X|Gs2]) :-
rs1_bn(Gs, [G|Gs1], Gs2).
rs1_bn([], _, []).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% gplan_to_rdf(GPlan, Facts).
% hmmm - the actions are inherently Quoted!
% *** vars - must be shared across: plan/pool/constraints/goal/start
gplan_goal_node_id(gplan(Nodes, _), Id) :-
memberchk(node('$goal',_)-Id, Nodes),
!.
gplan_goal_node_id(_, _) :-
err('No goal node found.').
gplan_to_obj(gplan(Nodes, Edges), TA, Objs) :-
map_node_to_obj(Nodes, TA, Nodes2),
map_add_edges(Edges, Nodes2, Nodes3),
map_val(Nodes3, Objs).
map_val([_-X|Xs], [X|Xs1]) :-
map_val(Xs, Xs1).
map_val([], []).
% *** ref/ids too - globalized http://...
map_add_edges([A-B|Es], Ns, Ns1) :-
( select(B-obj(Type, PVs), Ns, Ns2) ->
true
; err('Edge without target node ~q in plan graph.', [A-B])
),
PV = (inf_planFollows=obj(inf_PlanNode, [inf_ref=A])),
map_add_edges(Es, [B-obj(Type, [PV|PVs])|Ns2], Ns1).
map_add_edges([], Ns, Ns).
map_node_to_obj([X|Xs], TA, [X1|Xs1]) :-
node_to_obj(X, TA, X1),
map_node_to_obj(Xs, TA, Xs1).
map_node_to_obj([], _, []).
node_to_obj(X, TA, Id-Y) :-
X = node(Plain, _)-Id,
!,
plain_to_obj(Plain, TA, [], Action),
Y = obj(inf_PlanNode, [inf_ref=Id, inf_planAction=Action]).
node_to_obj(X, _, _) :-
err('Bad plan node source: ~q.', [X]).
%% *** Action - wrap to lit if not object form ?
uses_constraints(Task) :-
task_input_constraints(Task, Cs),
Cs \= [],
!.
uses_constraints(Task) :-
task_rules(Task, Rules),
member(Rule, Rules),
rule_constraints(Rule, Cs),
Cs \= [],
!.
% *** Q: avoid toplevel variable objects - is that possible, maybe
% test with a single type
fluent_declarations_for_bodies(Rules, Decls) :-
findall(declare(fluent, F),
( member(Rule, Rules),
rule_body(Rule, Body),
member(F1, Body),
functor(F1, P, N),
functor(F, P, N)
),
Decls1),
remove_subsumed_elements(Decls1, Decls).
rule_body(rule(_,_,X,_), X).
rule_constraints(rule(_,_,_,X), X).
| TeamSPoon/logicmoo_base | prolog/logicmoo/tptp/infra/src/task_plan.pl | Perl | mit | 8,921 |
/* Part of XPCE --- The SWI-Prolog GUI toolkit
Author: Jan Wielemaker and Anjo Anjewierden
E-mail: jan@swi.psy.uva.nl
WWW: http://www.swi.psy.uva.nl/projects/xpce/
Copyright (c) 1996-2011, University of Amsterdam
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
:- module(pce_shell,
[ pce_shell_command/1
]).
:- use_module(library(pce)).
:- require([ atomic_list_concat/3
]).
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pce_shell_command(+Command(..+Arg..)
Run an external command that is no supposed to produce output and
wait for it to terminate. The output of the command is captured
in a text_buffer. If the command fails, a view is created to show
the output and this predicate will fail.
This predicate is generally better then using Prolog's system/1,
shell/1 or unix/1 as it ensures event-handling during the execution
of the external command and presentation of possible output in a
window rather then to the Prolog window.
Example:
...
pce_shell_command(lpr('-PPostscript', File)),
...
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
pce_shell_command(Cmd) :-
Cmd =.. List,
ProcTerm =.. [process | List],
new(P, ProcTerm),
new(TB, text_buffer),
send(P, input_message,
and(message(@arg1, translate, 13, @nil),
message(TB, append, @arg1))),
send(P, record_separator, @nil),
atomic_list_concat(List, ' ', CmdAtom),
send(P, report, progress, 'running %s ...', CmdAtom),
send(P, open),
send(P, wait),
( get(P, code, 0)
-> send(P, report, done),
free(TB)
; get(P, code, Code),
( atom(Code)
-> send(P, report, error, 'Caught signal %s', Code)
; send(P, report, error, 'Exit status %s', Code)
),
new(V, view(string('Output of %s', CmdAtom))),
send(V, text_buffer, TB),
send(new(D, dialog), below, V),
send(D, append, button(quit, message(V, destroy))),
send(V?frame, confirm_done, @off),
send(V, open),
fail
).
| TeamSPoon/logicmoo_workspace | docker/rootfs/usr/local/lib/swipl/xpce/prolog/lib/pce_shell.pl | Perl | mit | 3,525 |
#! perl
# Getopt::Long.pm -- Universal options parsing
# Author : Johan Vromans
# Created On : Tue Sep 11 15:00:12 1990
# Last Modified By: Johan Vromans
# Last Modified On: Sat May 27 12:11:39 2017
# Update Count : 1715
# Status : Released
################ Module Preamble ################
use 5.004;
use strict;
use warnings;
package Getopt::Long;
use vars qw($VERSION);
$VERSION = 2.50;
# For testing versions only.
use vars qw($VERSION_STRING);
$VERSION_STRING = "2.50";
use Exporter;
use vars qw(@ISA @EXPORT @EXPORT_OK);
@ISA = qw(Exporter);
# Exported subroutines.
sub GetOptions(@); # always
sub GetOptionsFromArray(@); # on demand
sub GetOptionsFromString(@); # on demand
sub Configure(@); # on demand
sub HelpMessage(@); # on demand
sub VersionMessage(@); # in demand
BEGIN {
# Init immediately so their contents can be used in the 'use vars' below.
@EXPORT = qw(&GetOptions $REQUIRE_ORDER $PERMUTE $RETURN_IN_ORDER);
@EXPORT_OK = qw(&HelpMessage &VersionMessage &Configure
&GetOptionsFromArray &GetOptionsFromString);
}
# User visible variables.
use vars @EXPORT, @EXPORT_OK;
use vars qw($error $debug $major_version $minor_version);
# Deprecated visible variables.
use vars qw($autoabbrev $getopt_compat $ignorecase $bundling $order
$passthrough);
# Official invisible variables.
use vars qw($genprefix $caller $gnu_compat $auto_help $auto_version $longprefix);
# Really invisible variables.
my $bundling_values;
# Public subroutines.
sub config(@); # deprecated name
# Private subroutines.
sub ConfigDefaults();
sub ParseOptionSpec($$);
sub OptCtl($);
sub FindOption($$$$$);
sub ValidValue ($$$$$);
################ Local Variables ################
# $requested_version holds the version that was mentioned in the 'use'
# or 'require', if any. It can be used to enable or disable specific
# features.
my $requested_version = 0;
################ Resident subroutines ################
sub ConfigDefaults() {
# Handle POSIX compliancy.
if ( defined $ENV{"POSIXLY_CORRECT"} ) {
$genprefix = "(--|-)";
$autoabbrev = 0; # no automatic abbrev of options
$bundling = 0; # no bundling of single letter switches
$getopt_compat = 0; # disallow '+' to start options
$order = $REQUIRE_ORDER;
}
else {
$genprefix = "(--|-|\\+)";
$autoabbrev = 1; # automatic abbrev of options
$bundling = 0; # bundling off by default
$getopt_compat = 1; # allow '+' to start options
$order = $PERMUTE;
}
# Other configurable settings.
$debug = 0; # for debugging
$error = 0; # error tally
$ignorecase = 1; # ignore case when matching options
$passthrough = 0; # leave unrecognized options alone
$gnu_compat = 0; # require --opt=val if value is optional
$longprefix = "(--)"; # what does a long prefix look like
$bundling_values = 0; # no bundling of values
}
# Override import.
sub import {
my $pkg = shift; # package
my @syms = (); # symbols to import
my @config = (); # configuration
my $dest = \@syms; # symbols first
for ( @_ ) {
if ( $_ eq ':config' ) {
$dest = \@config; # config next
next;
}
push(@$dest, $_); # push
}
# Hide one level and call super.
local $Exporter::ExportLevel = 1;
push(@syms, qw(&GetOptions)) if @syms; # always export GetOptions
$requested_version = 0;
$pkg->SUPER::import(@syms);
# And configure.
Configure(@config) if @config;
}
################ Initialization ################
# Values for $order. See GNU getopt.c for details.
($REQUIRE_ORDER, $PERMUTE, $RETURN_IN_ORDER) = (0..2);
# Version major/minor numbers.
($major_version, $minor_version) = $VERSION =~ /^(\d+)\.(\d+)/;
ConfigDefaults();
################ OO Interface ################
package Getopt::Long::Parser;
# Store a copy of the default configuration. Since ConfigDefaults has
# just been called, what we get from Configure is the default.
my $default_config = do {
Getopt::Long::Configure ()
};
sub new {
my $that = shift;
my $class = ref($that) || $that;
my %atts = @_;
# Register the callers package.
my $self = { caller_pkg => (caller)[0] };
bless ($self, $class);
# Process config attributes.
if ( defined $atts{config} ) {
my $save = Getopt::Long::Configure ($default_config, @{$atts{config}});
$self->{settings} = Getopt::Long::Configure ($save);
delete ($atts{config});
}
# Else use default config.
else {
$self->{settings} = $default_config;
}
if ( %atts ) { # Oops
die(__PACKAGE__.": unhandled attributes: ".
join(" ", sort(keys(%atts)))."\n");
}
$self;
}
sub configure {
my ($self) = shift;
# Restore settings, merge new settings in.
my $save = Getopt::Long::Configure ($self->{settings}, @_);
# Restore orig config and save the new config.
$self->{settings} = Getopt::Long::Configure ($save);
}
sub getoptions {
my ($self) = shift;
return $self->getoptionsfromarray(\@ARGV, @_);
}
sub getoptionsfromarray {
my ($self) = shift;
# Restore config settings.
my $save = Getopt::Long::Configure ($self->{settings});
# Call main routine.
my $ret = 0;
$Getopt::Long::caller = $self->{caller_pkg};
eval {
# Locally set exception handler to default, otherwise it will
# be called implicitly here, and again explicitly when we try
# to deliver the messages.
local ($SIG{__DIE__}) = 'DEFAULT';
$ret = Getopt::Long::GetOptionsFromArray (@_);
};
# Restore saved settings.
Getopt::Long::Configure ($save);
# Handle errors and return value.
die ($@) if $@;
return $ret;
}
package Getopt::Long;
################ Back to Normal ################
# Indices in option control info.
# Note that ParseOptions uses the fields directly. Search for 'hard-wired'.
use constant CTL_TYPE => 0;
#use constant CTL_TYPE_FLAG => '';
#use constant CTL_TYPE_NEG => '!';
#use constant CTL_TYPE_INCR => '+';
#use constant CTL_TYPE_INT => 'i';
#use constant CTL_TYPE_INTINC => 'I';
#use constant CTL_TYPE_XINT => 'o';
#use constant CTL_TYPE_FLOAT => 'f';
#use constant CTL_TYPE_STRING => 's';
use constant CTL_CNAME => 1;
use constant CTL_DEFAULT => 2;
use constant CTL_DEST => 3;
use constant CTL_DEST_SCALAR => 0;
use constant CTL_DEST_ARRAY => 1;
use constant CTL_DEST_HASH => 2;
use constant CTL_DEST_CODE => 3;
use constant CTL_AMIN => 4;
use constant CTL_AMAX => 5;
# FFU.
#use constant CTL_RANGE => ;
#use constant CTL_REPEAT => ;
# Rather liberal patterns to match numbers.
use constant PAT_INT => "[-+]?_*[0-9][0-9_]*";
use constant PAT_XINT =>
"(?:".
"[-+]?_*[1-9][0-9_]*".
"|".
"0x_*[0-9a-f][0-9a-f_]*".
"|".
"0b_*[01][01_]*".
"|".
"0[0-7_]*".
")";
use constant PAT_FLOAT =>
"[-+]?". # optional sign
"(?=[0-9.])". # must start with digit or dec.point
"[0-9_]*". # digits before the dec.point
"(\.[0-9_]+)?". # optional fraction
"([eE][-+]?[0-9_]+)?"; # optional exponent
sub GetOptions(@) {
# Shift in default array.
unshift(@_, \@ARGV);
# Try to keep caller() and Carp consistent.
goto &GetOptionsFromArray;
}
sub GetOptionsFromString(@) {
my ($string) = shift;
require Text::ParseWords;
my $args = [ Text::ParseWords::shellwords($string) ];
$caller ||= (caller)[0]; # current context
my $ret = GetOptionsFromArray($args, @_);
return ( $ret, $args ) if wantarray;
if ( @$args ) {
$ret = 0;
warn("GetOptionsFromString: Excess data \"@$args\" in string \"$string\"\n");
}
$ret;
}
sub GetOptionsFromArray(@) {
my ($argv, @optionlist) = @_; # local copy of the option descriptions
my $argend = '--'; # option list terminator
my %opctl = (); # table of option specs
my $pkg = $caller || (caller)[0]; # current context
# Needed if linkage is omitted.
my @ret = (); # accum for non-options
my %linkage; # linkage
my $userlinkage; # user supplied HASH
my $opt; # current option
my $prefix = $genprefix; # current prefix
$error = '';
if ( $debug ) {
# Avoid some warnings if debugging.
local ($^W) = 0;
print STDERR
("Getopt::Long $Getopt::Long::VERSION ",
"called from package \"$pkg\".",
"\n ",
"argv: ",
defined($argv)
? UNIVERSAL::isa( $argv, 'ARRAY' ) ? "(@$argv)" : $argv
: "<undef>",
"\n ",
"autoabbrev=$autoabbrev,".
"bundling=$bundling,",
"bundling_values=$bundling_values,",
"getopt_compat=$getopt_compat,",
"gnu_compat=$gnu_compat,",
"order=$order,",
"\n ",
"ignorecase=$ignorecase,",
"requested_version=$requested_version,",
"passthrough=$passthrough,",
"genprefix=\"$genprefix\",",
"longprefix=\"$longprefix\".",
"\n");
}
# Check for ref HASH as first argument.
# First argument may be an object. It's OK to use this as long
# as it is really a hash underneath.
$userlinkage = undef;
if ( @optionlist && ref($optionlist[0]) and
UNIVERSAL::isa($optionlist[0],'HASH') ) {
$userlinkage = shift (@optionlist);
print STDERR ("=> user linkage: $userlinkage\n") if $debug;
}
# See if the first element of the optionlist contains option
# starter characters.
# Be careful not to interpret '<>' as option starters.
if ( @optionlist && $optionlist[0] =~ /^\W+$/
&& !($optionlist[0] eq '<>'
&& @optionlist > 0
&& ref($optionlist[1])) ) {
$prefix = shift (@optionlist);
# Turn into regexp. Needs to be parenthesized!
$prefix =~ s/(\W)/\\$1/g;
$prefix = "([" . $prefix . "])";
print STDERR ("=> prefix=\"$prefix\"\n") if $debug;
}
# Verify correctness of optionlist.
%opctl = ();
while ( @optionlist ) {
my $opt = shift (@optionlist);
unless ( defined($opt) ) {
$error .= "Undefined argument in option spec\n";
next;
}
# Strip leading prefix so people can specify "--foo=i" if they like.
$opt = $+ if $opt =~ /^$prefix+(.*)$/s;
if ( $opt eq '<>' ) {
if ( (defined $userlinkage)
&& !(@optionlist > 0 && ref($optionlist[0]))
&& (exists $userlinkage->{$opt})
&& ref($userlinkage->{$opt}) ) {
unshift (@optionlist, $userlinkage->{$opt});
}
unless ( @optionlist > 0
&& ref($optionlist[0]) && ref($optionlist[0]) eq 'CODE' ) {
$error .= "Option spec <> requires a reference to a subroutine\n";
# Kill the linkage (to avoid another error).
shift (@optionlist)
if @optionlist && ref($optionlist[0]);
next;
}
$linkage{'<>'} = shift (@optionlist);
next;
}
# Parse option spec.
my ($name, $orig) = ParseOptionSpec ($opt, \%opctl);
unless ( defined $name ) {
# Failed. $orig contains the error message. Sorry for the abuse.
$error .= $orig;
# Kill the linkage (to avoid another error).
shift (@optionlist)
if @optionlist && ref($optionlist[0]);
next;
}
# If no linkage is supplied in the @optionlist, copy it from
# the userlinkage if available.
if ( defined $userlinkage ) {
unless ( @optionlist > 0 && ref($optionlist[0]) ) {
if ( exists $userlinkage->{$orig} &&
ref($userlinkage->{$orig}) ) {
print STDERR ("=> found userlinkage for \"$orig\": ",
"$userlinkage->{$orig}\n")
if $debug;
unshift (@optionlist, $userlinkage->{$orig});
}
else {
# Do nothing. Being undefined will be handled later.
next;
}
}
}
# Copy the linkage. If omitted, link to global variable.
if ( @optionlist > 0 && ref($optionlist[0]) ) {
print STDERR ("=> link \"$orig\" to $optionlist[0]\n")
if $debug;
my $rl = ref($linkage{$orig} = shift (@optionlist));
if ( $rl eq "ARRAY" ) {
$opctl{$name}[CTL_DEST] = CTL_DEST_ARRAY;
}
elsif ( $rl eq "HASH" ) {
$opctl{$name}[CTL_DEST] = CTL_DEST_HASH;
}
elsif ( $rl eq "SCALAR" || $rl eq "REF" ) {
# if ( $opctl{$name}[CTL_DEST] == CTL_DEST_ARRAY ) {
# my $t = $linkage{$orig};
# $$t = $linkage{$orig} = [];
# }
# elsif ( $opctl{$name}[CTL_DEST] == CTL_DEST_HASH ) {
# }
# else {
# Ok.
# }
}
elsif ( $rl eq "CODE" ) {
# Ok.
}
else {
$error .= "Invalid option linkage for \"$opt\"\n";
}
}
else {
# Link to global $opt_XXX variable.
# Make sure a valid perl identifier results.
my $ov = $orig;
$ov =~ s/\W/_/g;
if ( $opctl{$name}[CTL_DEST] == CTL_DEST_ARRAY ) {
print STDERR ("=> link \"$orig\" to \@$pkg","::opt_$ov\n")
if $debug;
eval ("\$linkage{\$orig} = \\\@".$pkg."::opt_$ov;");
}
elsif ( $opctl{$name}[CTL_DEST] == CTL_DEST_HASH ) {
print STDERR ("=> link \"$orig\" to \%$pkg","::opt_$ov\n")
if $debug;
eval ("\$linkage{\$orig} = \\\%".$pkg."::opt_$ov;");
}
else {
print STDERR ("=> link \"$orig\" to \$$pkg","::opt_$ov\n")
if $debug;
eval ("\$linkage{\$orig} = \\\$".$pkg."::opt_$ov;");
}
}
if ( $opctl{$name}[CTL_TYPE] eq 'I'
&& ( $opctl{$name}[CTL_DEST] == CTL_DEST_ARRAY
|| $opctl{$name}[CTL_DEST] == CTL_DEST_HASH )
) {
$error .= "Invalid option linkage for \"$opt\"\n";
}
}
$error .= "GetOptionsFromArray: 1st parameter is not an array reference\n"
unless $argv && UNIVERSAL::isa( $argv, 'ARRAY' );
# Bail out if errors found.
die ($error) if $error;
$error = 0;
# Supply --version and --help support, if needed and allowed.
if ( defined($auto_version) ? $auto_version : ($requested_version >= 2.3203) ) {
if ( !defined($opctl{version}) ) {
$opctl{version} = ['','version',0,CTL_DEST_CODE,undef];
$linkage{version} = \&VersionMessage;
}
$auto_version = 1;
}
if ( defined($auto_help) ? $auto_help : ($requested_version >= 2.3203) ) {
if ( !defined($opctl{help}) && !defined($opctl{'?'}) ) {
$opctl{help} = $opctl{'?'} = ['','help',0,CTL_DEST_CODE,undef];
$linkage{help} = \&HelpMessage;
}
$auto_help = 1;
}
# Show the options tables if debugging.
if ( $debug ) {
my ($arrow, $k, $v);
$arrow = "=> ";
while ( ($k,$v) = each(%opctl) ) {
print STDERR ($arrow, "\$opctl{$k} = $v ", OptCtl($v), "\n");
$arrow = " ";
}
}
# Process argument list
my $goon = 1;
while ( $goon && @$argv > 0 ) {
# Get next argument.
$opt = shift (@$argv);
print STDERR ("=> arg \"", $opt, "\"\n") if $debug;
# Double dash is option list terminator.
if ( defined($opt) && $opt eq $argend ) {
push (@ret, $argend) if $passthrough;
last;
}
# Look it up.
my $tryopt = $opt;
my $found; # success status
my $key; # key (if hash type)
my $arg; # option argument
my $ctl; # the opctl entry
($found, $opt, $ctl, $arg, $key) =
FindOption ($argv, $prefix, $argend, $opt, \%opctl);
if ( $found ) {
# FindOption undefines $opt in case of errors.
next unless defined $opt;
my $argcnt = 0;
while ( defined $arg ) {
# Get the canonical name.
print STDERR ("=> cname for \"$opt\" is ") if $debug;
$opt = $ctl->[CTL_CNAME];
print STDERR ("\"$ctl->[CTL_CNAME]\"\n") if $debug;
if ( defined $linkage{$opt} ) {
print STDERR ("=> ref(\$L{$opt}) -> ",
ref($linkage{$opt}), "\n") if $debug;
if ( ref($linkage{$opt}) eq 'SCALAR'
|| ref($linkage{$opt}) eq 'REF' ) {
if ( $ctl->[CTL_TYPE] eq '+' ) {
print STDERR ("=> \$\$L{$opt} += \"$arg\"\n")
if $debug;
if ( defined ${$linkage{$opt}} ) {
${$linkage{$opt}} += $arg;
}
else {
${$linkage{$opt}} = $arg;
}
}
elsif ( $ctl->[CTL_DEST] == CTL_DEST_ARRAY ) {
print STDERR ("=> ref(\$L{$opt}) auto-vivified",
" to ARRAY\n")
if $debug;
my $t = $linkage{$opt};
$$t = $linkage{$opt} = [];
print STDERR ("=> push(\@{\$L{$opt}, \"$arg\")\n")
if $debug;
push (@{$linkage{$opt}}, $arg);
}
elsif ( $ctl->[CTL_DEST] == CTL_DEST_HASH ) {
print STDERR ("=> ref(\$L{$opt}) auto-vivified",
" to HASH\n")
if $debug;
my $t = $linkage{$opt};
$$t = $linkage{$opt} = {};
print STDERR ("=> \$\$L{$opt}->{$key} = \"$arg\"\n")
if $debug;
$linkage{$opt}->{$key} = $arg;
}
else {
print STDERR ("=> \$\$L{$opt} = \"$arg\"\n")
if $debug;
${$linkage{$opt}} = $arg;
}
}
elsif ( ref($linkage{$opt}) eq 'ARRAY' ) {
print STDERR ("=> push(\@{\$L{$opt}, \"$arg\")\n")
if $debug;
push (@{$linkage{$opt}}, $arg);
}
elsif ( ref($linkage{$opt}) eq 'HASH' ) {
print STDERR ("=> \$\$L{$opt}->{$key} = \"$arg\"\n")
if $debug;
$linkage{$opt}->{$key} = $arg;
}
elsif ( ref($linkage{$opt}) eq 'CODE' ) {
print STDERR ("=> &L{$opt}(\"$opt\"",
$ctl->[CTL_DEST] == CTL_DEST_HASH ? ", \"$key\"" : "",
", \"$arg\")\n")
if $debug;
my $eval_error = do {
local $@;
local $SIG{__DIE__} = 'DEFAULT';
eval {
&{$linkage{$opt}}
(Getopt::Long::CallBack->new
(name => $opt,
ctl => $ctl,
opctl => \%opctl,
linkage => \%linkage,
prefix => $prefix,
),
$ctl->[CTL_DEST] == CTL_DEST_HASH ? ($key) : (),
$arg);
};
$@;
};
print STDERR ("=> die($eval_error)\n")
if $debug && $eval_error ne '';
if ( $eval_error =~ /^!/ ) {
if ( $eval_error =~ /^!FINISH\b/ ) {
$goon = 0;
}
}
elsif ( $eval_error ne '' ) {
warn ($eval_error);
$error++;
}
}
else {
print STDERR ("Invalid REF type \"", ref($linkage{$opt}),
"\" in linkage\n");
die("Getopt::Long -- internal error!\n");
}
}
# No entry in linkage means entry in userlinkage.
elsif ( $ctl->[CTL_DEST] == CTL_DEST_ARRAY ) {
if ( defined $userlinkage->{$opt} ) {
print STDERR ("=> push(\@{\$L{$opt}}, \"$arg\")\n")
if $debug;
push (@{$userlinkage->{$opt}}, $arg);
}
else {
print STDERR ("=>\$L{$opt} = [\"$arg\"]\n")
if $debug;
$userlinkage->{$opt} = [$arg];
}
}
elsif ( $ctl->[CTL_DEST] == CTL_DEST_HASH ) {
if ( defined $userlinkage->{$opt} ) {
print STDERR ("=> \$L{$opt}->{$key} = \"$arg\"\n")
if $debug;
$userlinkage->{$opt}->{$key} = $arg;
}
else {
print STDERR ("=>\$L{$opt} = {$key => \"$arg\"}\n")
if $debug;
$userlinkage->{$opt} = {$key => $arg};
}
}
else {
if ( $ctl->[CTL_TYPE] eq '+' ) {
print STDERR ("=> \$L{$opt} += \"$arg\"\n")
if $debug;
if ( defined $userlinkage->{$opt} ) {
$userlinkage->{$opt} += $arg;
}
else {
$userlinkage->{$opt} = $arg;
}
}
else {
print STDERR ("=>\$L{$opt} = \"$arg\"\n") if $debug;
$userlinkage->{$opt} = $arg;
}
}
$argcnt++;
last if $argcnt >= $ctl->[CTL_AMAX] && $ctl->[CTL_AMAX] != -1;
undef($arg);
# Need more args?
if ( $argcnt < $ctl->[CTL_AMIN] ) {
if ( @$argv ) {
if ( ValidValue($ctl, $argv->[0], 1, $argend, $prefix) ) {
$arg = shift(@$argv);
if ( $ctl->[CTL_TYPE] =~ /^[iIo]$/ ) {
$arg =~ tr/_//d;
$arg = $ctl->[CTL_TYPE] eq 'o' && $arg =~ /^0/
? oct($arg)
: 0+$arg
}
($key,$arg) = $arg =~ /^([^=]+)=(.*)/
if $ctl->[CTL_DEST] == CTL_DEST_HASH;
next;
}
warn("Value \"$$argv[0]\" invalid for option $opt\n");
$error++;
}
else {
warn("Insufficient arguments for option $opt\n");
$error++;
}
}
# Any more args?
if ( @$argv && ValidValue($ctl, $argv->[0], 0, $argend, $prefix) ) {
$arg = shift(@$argv);
if ( $ctl->[CTL_TYPE] =~ /^[iIo]$/ ) {
$arg =~ tr/_//d;
$arg = $ctl->[CTL_TYPE] eq 'o' && $arg =~ /^0/
? oct($arg)
: 0+$arg
}
($key,$arg) = $arg =~ /^([^=]+)=(.*)/
if $ctl->[CTL_DEST] == CTL_DEST_HASH;
next;
}
}
}
# Not an option. Save it if we $PERMUTE and don't have a <>.
elsif ( $order == $PERMUTE ) {
# Try non-options call-back.
my $cb;
if ( defined ($cb = $linkage{'<>'}) ) {
print STDERR ("=> &L{$tryopt}(\"$tryopt\")\n")
if $debug;
my $eval_error = do {
local $@;
local $SIG{__DIE__} = 'DEFAULT';
eval {
# The arg to <> cannot be the CallBack object
# since it may be passed to other modules that
# get confused (e.g., Archive::Tar). Well,
# it's not relevant for this callback anyway.
&$cb($tryopt);
};
$@;
};
print STDERR ("=> die($eval_error)\n")
if $debug && $eval_error ne '';
if ( $eval_error =~ /^!/ ) {
if ( $eval_error =~ /^!FINISH\b/ ) {
$goon = 0;
}
}
elsif ( $eval_error ne '' ) {
warn ($eval_error);
$error++;
}
}
else {
print STDERR ("=> saving \"$tryopt\" ",
"(not an option, may permute)\n") if $debug;
push (@ret, $tryopt);
}
next;
}
# ...otherwise, terminate.
else {
# Push this one back and exit.
unshift (@$argv, $tryopt);
return ($error == 0);
}
}
# Finish.
if ( @ret && $order == $PERMUTE ) {
# Push back accumulated arguments
print STDERR ("=> restoring \"", join('" "', @ret), "\"\n")
if $debug;
unshift (@$argv, @ret);
}
return ($error == 0);
}
# A readable representation of what's in an optbl.
sub OptCtl ($) {
my ($v) = @_;
my @v = map { defined($_) ? ($_) : ("<undef>") } @$v;
"[".
join(",",
"\"$v[CTL_TYPE]\"",
"\"$v[CTL_CNAME]\"",
"\"$v[CTL_DEFAULT]\"",
("\$","\@","\%","\&")[$v[CTL_DEST] || 0],
$v[CTL_AMIN] || '',
$v[CTL_AMAX] || '',
# $v[CTL_RANGE] || '',
# $v[CTL_REPEAT] || '',
). "]";
}
# Parse an option specification and fill the tables.
sub ParseOptionSpec ($$) {
my ($opt, $opctl) = @_;
# Match option spec.
if ( $opt !~ m;^
(
# Option name
(?: \w+[-\w]* )
# Alias names, or "?"
(?: \| (?: \? | \w[-\w]* ) )*
# Aliases
(?: \| (?: [^-|!+=:][^|!+=:]* )? )*
)?
(
# Either modifiers ...
[!+]
|
# ... or a value/dest/repeat specification
[=:] [ionfs] [@%]? (?: \{\d*,?\d*\} )?
|
# ... or an optional-with-default spec
: (?: -?\d+ | \+ ) [@%]?
)?
$;x ) {
return (undef, "Error in option spec: \"$opt\"\n");
}
my ($names, $spec) = ($1, $2);
$spec = '' unless defined $spec;
# $orig keeps track of the primary name the user specified.
# This name will be used for the internal or external linkage.
# In other words, if the user specifies "FoO|BaR", it will
# match any case combinations of 'foo' and 'bar', but if a global
# variable needs to be set, it will be $opt_FoO in the exact case
# as specified.
my $orig;
my @names;
if ( defined $names ) {
@names = split (/\|/, $names);
$orig = $names[0];
}
else {
@names = ('');
$orig = '';
}
# Construct the opctl entries.
my $entry;
if ( $spec eq '' || $spec eq '+' || $spec eq '!' ) {
# Fields are hard-wired here.
$entry = [$spec,$orig,undef,CTL_DEST_SCALAR,0,0];
}
elsif ( $spec =~ /^:(-?\d+|\+)([@%])?$/ ) {
my $def = $1;
my $dest = $2;
my $type = $def eq '+' ? 'I' : 'i';
$dest ||= '$';
$dest = $dest eq '@' ? CTL_DEST_ARRAY
: $dest eq '%' ? CTL_DEST_HASH : CTL_DEST_SCALAR;
# Fields are hard-wired here.
$entry = [$type,$orig,$def eq '+' ? undef : $def,
$dest,0,1];
}
else {
my ($mand, $type, $dest) =
$spec =~ /^([=:])([ionfs])([@%])?(\{(\d+)?(,)?(\d+)?\})?$/;
return (undef, "Cannot repeat while bundling: \"$opt\"\n")
if $bundling && defined($4);
my ($mi, $cm, $ma) = ($5, $6, $7);
return (undef, "{0} is useless in option spec: \"$opt\"\n")
if defined($mi) && !$mi && !defined($ma) && !defined($cm);
$type = 'i' if $type eq 'n';
$dest ||= '$';
$dest = $dest eq '@' ? CTL_DEST_ARRAY
: $dest eq '%' ? CTL_DEST_HASH : CTL_DEST_SCALAR;
# Default minargs to 1/0 depending on mand status.
$mi = $mand eq '=' ? 1 : 0 unless defined $mi;
# Adjust mand status according to minargs.
$mand = $mi ? '=' : ':';
# Adjust maxargs.
$ma = $mi ? $mi : 1 unless defined $ma || defined $cm;
return (undef, "Max must be greater than zero in option spec: \"$opt\"\n")
if defined($ma) && !$ma;
return (undef, "Max less than min in option spec: \"$opt\"\n")
if defined($ma) && $ma < $mi;
# Fields are hard-wired here.
$entry = [$type,$orig,undef,$dest,$mi,$ma||-1];
}
# Process all names. First is canonical, the rest are aliases.
my $dups = '';
foreach ( @names ) {
$_ = lc ($_)
if $ignorecase > (($bundling && length($_) == 1) ? 1 : 0);
if ( exists $opctl->{$_} ) {
$dups .= "Duplicate specification \"$opt\" for option \"$_\"\n";
}
if ( $spec eq '!' ) {
$opctl->{"no$_"} = $entry;
$opctl->{"no-$_"} = $entry;
$opctl->{$_} = [@$entry];
$opctl->{$_}->[CTL_TYPE] = '';
}
else {
$opctl->{$_} = $entry;
}
}
if ( $dups && $^W ) {
foreach ( split(/\n+/, $dups) ) {
warn($_."\n");
}
}
($names[0], $orig);
}
# Option lookup.
sub FindOption ($$$$$) {
# returns (1, $opt, $ctl, $arg, $key) if okay,
# returns (1, undef) if option in error,
# returns (0) otherwise.
my ($argv, $prefix, $argend, $opt, $opctl) = @_;
print STDERR ("=> find \"$opt\"\n") if $debug;
return (0) unless defined($opt);
return (0) unless $opt =~ /^($prefix)(.*)$/s;
return (0) if $opt eq "-" && !defined $opctl->{''};
$opt = substr( $opt, length($1) ); # retain taintedness
my $starter = $1;
print STDERR ("=> split \"$starter\"+\"$opt\"\n") if $debug;
my $optarg; # value supplied with --opt=value
my $rest; # remainder from unbundling
# If it is a long option, it may include the value.
# With getopt_compat, only if not bundling.
if ( ($starter=~/^$longprefix$/
|| ($getopt_compat && ($bundling == 0 || $bundling == 2)))
&& (my $oppos = index($opt, '=', 1)) > 0) {
my $optorg = $opt;
$opt = substr($optorg, 0, $oppos);
$optarg = substr($optorg, $oppos + 1); # retain tainedness
print STDERR ("=> option \"", $opt,
"\", optarg = \"$optarg\"\n") if $debug;
}
#### Look it up ###
my $tryopt = $opt; # option to try
if ( ( $bundling || $bundling_values ) && $starter eq '-' ) {
# To try overrides, obey case ignore.
$tryopt = $ignorecase ? lc($opt) : $opt;
# If bundling == 2, long options can override bundles.
if ( $bundling == 2 && length($tryopt) > 1
&& defined ($opctl->{$tryopt}) ) {
print STDERR ("=> $starter$tryopt overrides unbundling\n")
if $debug;
}
# If bundling_values, option may be followed by the value.
elsif ( $bundling_values ) {
$tryopt = $opt;
# Unbundle single letter option.
$rest = length ($tryopt) > 0 ? substr ($tryopt, 1) : '';
$tryopt = substr ($tryopt, 0, 1);
$tryopt = lc ($tryopt) if $ignorecase > 1;
print STDERR ("=> $starter$tryopt unbundled from ",
"$starter$tryopt$rest\n") if $debug;
# Whatever remains may not be considered an option.
$optarg = $rest eq '' ? undef : $rest;
$rest = undef;
}
# Split off a single letter and leave the rest for
# further processing.
else {
$tryopt = $opt;
# Unbundle single letter option.
$rest = length ($tryopt) > 0 ? substr ($tryopt, 1) : '';
$tryopt = substr ($tryopt, 0, 1);
$tryopt = lc ($tryopt) if $ignorecase > 1;
print STDERR ("=> $starter$tryopt unbundled from ",
"$starter$tryopt$rest\n") if $debug;
$rest = undef unless $rest ne '';
}
}
# Try auto-abbreviation.
elsif ( $autoabbrev && $opt ne "" ) {
# Sort the possible long option names.
my @names = sort(keys (%$opctl));
# Downcase if allowed.
$opt = lc ($opt) if $ignorecase;
$tryopt = $opt;
# Turn option name into pattern.
my $pat = quotemeta ($opt);
# Look up in option names.
my @hits = grep (/^$pat/, @names);
print STDERR ("=> ", scalar(@hits), " hits (@hits) with \"$pat\" ",
"out of ", scalar(@names), "\n") if $debug;
# Check for ambiguous results.
unless ( (@hits <= 1) || (grep ($_ eq $opt, @hits) == 1) ) {
# See if all matches are for the same option.
my %hit;
foreach ( @hits ) {
my $hit = $opctl->{$_}->[CTL_CNAME]
if defined $opctl->{$_}->[CTL_CNAME];
$hit = "no" . $hit if $opctl->{$_}->[CTL_TYPE] eq '!';
$hit{$hit} = 1;
}
# Remove auto-supplied options (version, help).
if ( keys(%hit) == 2 ) {
if ( $auto_version && exists($hit{version}) ) {
delete $hit{version};
}
elsif ( $auto_help && exists($hit{help}) ) {
delete $hit{help};
}
}
# Now see if it really is ambiguous.
unless ( keys(%hit) == 1 ) {
return (0) if $passthrough;
warn ("Option ", $opt, " is ambiguous (",
join(", ", @hits), ")\n");
$error++;
return (1, undef);
}
@hits = keys(%hit);
}
# Complete the option name, if appropriate.
if ( @hits == 1 && $hits[0] ne $opt ) {
$tryopt = $hits[0];
$tryopt = lc ($tryopt)
if $ignorecase > (($bundling && length($tryopt) == 1) ? 1 : 0);
print STDERR ("=> option \"$opt\" -> \"$tryopt\"\n")
if $debug;
}
}
# Map to all lowercase if ignoring case.
elsif ( $ignorecase ) {
$tryopt = lc ($opt);
}
# Check validity by fetching the info.
my $ctl = $opctl->{$tryopt};
unless ( defined $ctl ) {
return (0) if $passthrough;
# Pretend one char when bundling.
if ( $bundling == 1 && length($starter) == 1 ) {
$opt = substr($opt,0,1);
unshift (@$argv, $starter.$rest) if defined $rest;
}
if ( $opt eq "" ) {
warn ("Missing option after ", $starter, "\n");
}
else {
warn ("Unknown option: ", $opt, "\n");
}
$error++;
return (1, undef);
}
# Apparently valid.
$opt = $tryopt;
print STDERR ("=> found ", OptCtl($ctl),
" for \"", $opt, "\"\n") if $debug;
#### Determine argument status ####
# If it is an option w/o argument, we're almost finished with it.
my $type = $ctl->[CTL_TYPE];
my $arg;
if ( $type eq '' || $type eq '!' || $type eq '+' ) {
if ( defined $optarg ) {
return (0) if $passthrough;
warn ("Option ", $opt, " does not take an argument\n");
$error++;
undef $opt;
undef $optarg if $bundling_values;
}
elsif ( $type eq '' || $type eq '+' ) {
# Supply explicit value.
$arg = 1;
}
else {
$opt =~ s/^no-?//i; # strip NO prefix
$arg = 0; # supply explicit value
}
unshift (@$argv, $starter.$rest) if defined $rest;
return (1, $opt, $ctl, $arg);
}
# Get mandatory status and type info.
my $mand = $ctl->[CTL_AMIN];
# Check if there is an option argument available.
if ( $gnu_compat ) {
my $optargtype = 0; # none, 1 = empty, 2 = nonempty, 3 = aux
if ( defined($optarg) ) {
$optargtype = (length($optarg) == 0) ? 1 : 2;
}
elsif ( defined $rest || @$argv > 0 ) {
# GNU getopt_long() does not accept the (optional)
# argument to be passed to the option without = sign.
# We do, since not doing so breaks existing scripts.
$optargtype = 3;
}
if(($optargtype == 0) && !$mand) {
my $val
= defined($ctl->[CTL_DEFAULT]) ? $ctl->[CTL_DEFAULT]
: $type eq 's' ? ''
: 0;
return (1, $opt, $ctl, $val);
}
return (1, $opt, $ctl, $type eq 's' ? '' : 0)
if $optargtype == 1; # --foo= -> return nothing
}
# Check if there is an option argument available.
if ( defined $optarg
? ($optarg eq '')
: !(defined $rest || @$argv > 0) ) {
# Complain if this option needs an argument.
# if ( $mand && !($type eq 's' ? defined($optarg) : 0) ) {
if ( $mand ) {
return (0) if $passthrough;
warn ("Option ", $opt, " requires an argument\n");
$error++;
return (1, undef);
}
if ( $type eq 'I' ) {
# Fake incremental type.
my @c = @$ctl;
$c[CTL_TYPE] = '+';
return (1, $opt, \@c, 1);
}
return (1, $opt, $ctl,
defined($ctl->[CTL_DEFAULT]) ? $ctl->[CTL_DEFAULT] :
$type eq 's' ? '' : 0);
}
# Get (possibly optional) argument.
$arg = (defined $rest ? $rest
: (defined $optarg ? $optarg : shift (@$argv)));
# Get key if this is a "name=value" pair for a hash option.
my $key;
if ($ctl->[CTL_DEST] == CTL_DEST_HASH && defined $arg) {
($key, $arg) = ($arg =~ /^([^=]*)=(.*)$/s) ? ($1, $2)
: ($arg, defined($ctl->[CTL_DEFAULT]) ? $ctl->[CTL_DEFAULT] :
($mand ? undef : ($type eq 's' ? "" : 1)));
if (! defined $arg) {
warn ("Option $opt, key \"$key\", requires a value\n");
$error++;
# Push back.
unshift (@$argv, $starter.$rest) if defined $rest;
return (1, undef);
}
}
#### Check if the argument is valid for this option ####
my $key_valid = $ctl->[CTL_DEST] == CTL_DEST_HASH ? "[^=]+=" : "";
if ( $type eq 's' ) { # string
# A mandatory string takes anything.
return (1, $opt, $ctl, $arg, $key) if $mand;
# Same for optional string as a hash value
return (1, $opt, $ctl, $arg, $key)
if $ctl->[CTL_DEST] == CTL_DEST_HASH;
# An optional string takes almost anything.
return (1, $opt, $ctl, $arg, $key)
if defined $optarg || defined $rest;
return (1, $opt, $ctl, $arg, $key) if $arg eq "-"; # ??
# Check for option or option list terminator.
if ($arg eq $argend ||
$arg =~ /^$prefix.+/) {
# Push back.
unshift (@$argv, $arg);
# Supply empty value.
$arg = '';
}
}
elsif ( $type eq 'i' # numeric/integer
|| $type eq 'I' # numeric/integer w/ incr default
|| $type eq 'o' ) { # dec/oct/hex/bin value
my $o_valid = $type eq 'o' ? PAT_XINT : PAT_INT;
if ( $bundling && defined $rest
&& $rest =~ /^($key_valid)($o_valid)(.*)$/si ) {
($key, $arg, $rest) = ($1, $2, $+);
chop($key) if $key;
$arg = ($type eq 'o' && $arg =~ /^0/) ? oct($arg) : 0+$arg;
unshift (@$argv, $starter.$rest) if defined $rest && $rest ne '';
}
elsif ( $arg =~ /^$o_valid$/si ) {
$arg =~ tr/_//d;
$arg = ($type eq 'o' && $arg =~ /^0/) ? oct($arg) : 0+$arg;
}
else {
if ( defined $optarg || $mand ) {
if ( $passthrough ) {
unshift (@$argv, defined $rest ? $starter.$rest : $arg)
unless defined $optarg;
return (0);
}
warn ("Value \"", $arg, "\" invalid for option ",
$opt, " (",
$type eq 'o' ? "extended " : '',
"number expected)\n");
$error++;
# Push back.
unshift (@$argv, $starter.$rest) if defined $rest;
return (1, undef);
}
else {
# Push back.
unshift (@$argv, defined $rest ? $starter.$rest : $arg);
if ( $type eq 'I' ) {
# Fake incremental type.
my @c = @$ctl;
$c[CTL_TYPE] = '+';
return (1, $opt, \@c, 1);
}
# Supply default value.
$arg = defined($ctl->[CTL_DEFAULT]) ? $ctl->[CTL_DEFAULT] : 0;
}
}
}
elsif ( $type eq 'f' ) { # real number, int is also ok
my $o_valid = PAT_FLOAT;
if ( $bundling && defined $rest &&
$rest =~ /^($key_valid)($o_valid)(.*)$/s ) {
$arg =~ tr/_//d;
($key, $arg, $rest) = ($1, $2, $+);
chop($key) if $key;
unshift (@$argv, $starter.$rest) if defined $rest && $rest ne '';
}
elsif ( $arg =~ /^$o_valid$/ ) {
$arg =~ tr/_//d;
}
else {
if ( defined $optarg || $mand ) {
if ( $passthrough ) {
unshift (@$argv, defined $rest ? $starter.$rest : $arg)
unless defined $optarg;
return (0);
}
warn ("Value \"", $arg, "\" invalid for option ",
$opt, " (real number expected)\n");
$error++;
# Push back.
unshift (@$argv, $starter.$rest) if defined $rest;
return (1, undef);
}
else {
# Push back.
unshift (@$argv, defined $rest ? $starter.$rest : $arg);
# Supply default value.
$arg = 0.0;
}
}
}
else {
die("Getopt::Long internal error (Can't happen)\n");
}
return (1, $opt, $ctl, $arg, $key);
}
sub ValidValue ($$$$$) {
my ($ctl, $arg, $mand, $argend, $prefix) = @_;
if ( $ctl->[CTL_DEST] == CTL_DEST_HASH ) {
return 0 unless $arg =~ /[^=]+=(.*)/;
$arg = $1;
}
my $type = $ctl->[CTL_TYPE];
if ( $type eq 's' ) { # string
# A mandatory string takes anything.
return (1) if $mand;
return (1) if $arg eq "-";
# Check for option or option list terminator.
return 0 if $arg eq $argend || $arg =~ /^$prefix.+/;
return 1;
}
elsif ( $type eq 'i' # numeric/integer
|| $type eq 'I' # numeric/integer w/ incr default
|| $type eq 'o' ) { # dec/oct/hex/bin value
my $o_valid = $type eq 'o' ? PAT_XINT : PAT_INT;
return $arg =~ /^$o_valid$/si;
}
elsif ( $type eq 'f' ) { # real number, int is also ok
my $o_valid = PAT_FLOAT;
return $arg =~ /^$o_valid$/;
}
die("ValidValue: Cannot happen\n");
}
# Getopt::Long Configuration.
sub Configure (@) {
my (@options) = @_;
my $prevconfig =
[ $error, $debug, $major_version, $minor_version, $caller,
$autoabbrev, $getopt_compat, $ignorecase, $bundling, $order,
$gnu_compat, $passthrough, $genprefix, $auto_version, $auto_help,
$longprefix, $bundling_values ];
if ( ref($options[0]) eq 'ARRAY' ) {
( $error, $debug, $major_version, $minor_version, $caller,
$autoabbrev, $getopt_compat, $ignorecase, $bundling, $order,
$gnu_compat, $passthrough, $genprefix, $auto_version, $auto_help,
$longprefix, $bundling_values ) = @{shift(@options)};
}
my $opt;
foreach $opt ( @options ) {
my $try = lc ($opt);
my $action = 1;
if ( $try =~ /^no_?(.*)$/s ) {
$action = 0;
$try = $+;
}
if ( ($try eq 'default' or $try eq 'defaults') && $action ) {
ConfigDefaults ();
}
elsif ( ($try eq 'posix_default' or $try eq 'posix_defaults') ) {
local $ENV{POSIXLY_CORRECT};
$ENV{POSIXLY_CORRECT} = 1 if $action;
ConfigDefaults ();
}
elsif ( $try eq 'auto_abbrev' or $try eq 'autoabbrev' ) {
$autoabbrev = $action;
}
elsif ( $try eq 'getopt_compat' ) {
$getopt_compat = $action;
$genprefix = $action ? "(--|-|\\+)" : "(--|-)";
}
elsif ( $try eq 'gnu_getopt' ) {
if ( $action ) {
$gnu_compat = 1;
$bundling = 1;
$getopt_compat = 0;
$genprefix = "(--|-)";
$order = $PERMUTE;
$bundling_values = 0;
}
}
elsif ( $try eq 'gnu_compat' ) {
$gnu_compat = $action;
$bundling = 0;
$bundling_values = 1;
}
elsif ( $try =~ /^(auto_?)?version$/ ) {
$auto_version = $action;
}
elsif ( $try =~ /^(auto_?)?help$/ ) {
$auto_help = $action;
}
elsif ( $try eq 'ignorecase' or $try eq 'ignore_case' ) {
$ignorecase = $action;
}
elsif ( $try eq 'ignorecase_always' or $try eq 'ignore_case_always' ) {
$ignorecase = $action ? 2 : 0;
}
elsif ( $try eq 'bundling' ) {
$bundling = $action;
$bundling_values = 0 if $action;
}
elsif ( $try eq 'bundling_override' ) {
$bundling = $action ? 2 : 0;
$bundling_values = 0 if $action;
}
elsif ( $try eq 'bundling_values' ) {
$bundling_values = $action;
$bundling = 0 if $action;
}
elsif ( $try eq 'require_order' ) {
$order = $action ? $REQUIRE_ORDER : $PERMUTE;
}
elsif ( $try eq 'permute' ) {
$order = $action ? $PERMUTE : $REQUIRE_ORDER;
}
elsif ( $try eq 'pass_through' or $try eq 'passthrough' ) {
$passthrough = $action;
}
elsif ( $try =~ /^prefix=(.+)$/ && $action ) {
$genprefix = $1;
# Turn into regexp. Needs to be parenthesized!
$genprefix = "(" . quotemeta($genprefix) . ")";
eval { '' =~ /$genprefix/; };
die("Getopt::Long: invalid pattern \"$genprefix\"\n") if $@;
}
elsif ( $try =~ /^prefix_pattern=(.+)$/ && $action ) {
$genprefix = $1;
# Parenthesize if needed.
$genprefix = "(" . $genprefix . ")"
unless $genprefix =~ /^\(.*\)$/;
eval { '' =~ m"$genprefix"; };
die("Getopt::Long: invalid pattern \"$genprefix\"\n") if $@;
}
elsif ( $try =~ /^long_prefix_pattern=(.+)$/ && $action ) {
$longprefix = $1;
# Parenthesize if needed.
$longprefix = "(" . $longprefix . ")"
unless $longprefix =~ /^\(.*\)$/;
eval { '' =~ m"$longprefix"; };
die("Getopt::Long: invalid long prefix pattern \"$longprefix\"\n") if $@;
}
elsif ( $try eq 'debug' ) {
$debug = $action;
}
else {
die("Getopt::Long: unknown or erroneous config parameter \"$opt\"\n")
}
}
$prevconfig;
}
# Deprecated name.
sub config (@) {
Configure (@_);
}
# Issue a standard message for --version.
#
# The arguments are mostly the same as for Pod::Usage::pod2usage:
#
# - a number (exit value)
# - a string (lead in message)
# - a hash with options. See Pod::Usage for details.
#
sub VersionMessage(@) {
# Massage args.
my $pa = setup_pa_args("version", @_);
my $v = $main::VERSION;
my $fh = $pa->{-output} ||
( ($pa->{-exitval} eq "NOEXIT" || $pa->{-exitval} < 2) ? \*STDOUT : \*STDERR );
print $fh (defined($pa->{-message}) ? $pa->{-message} : (),
$0, defined $v ? " version $v" : (),
"\n",
"(", __PACKAGE__, "::", "GetOptions",
" version ",
defined($Getopt::Long::VERSION_STRING)
? $Getopt::Long::VERSION_STRING : $VERSION, ";",
" Perl version ",
$] >= 5.006 ? sprintf("%vd", $^V) : $],
")\n");
exit($pa->{-exitval}) unless $pa->{-exitval} eq "NOEXIT";
}
# Issue a standard message for --help.
#
# The arguments are the same as for Pod::Usage::pod2usage:
#
# - a number (exit value)
# - a string (lead in message)
# - a hash with options. See Pod::Usage for details.
#
sub HelpMessage(@) {
eval {
require Pod::Usage;
import Pod::Usage;
1;
} || die("Cannot provide help: cannot load Pod::Usage\n");
# Note that pod2usage will issue a warning if -exitval => NOEXIT.
pod2usage(setup_pa_args("help", @_));
}
# Helper routine to set up a normalized hash ref to be used as
# argument to pod2usage.
sub setup_pa_args($@) {
my $tag = shift; # who's calling
# If called by direct binding to an option, it will get the option
# name and value as arguments. Remove these, if so.
@_ = () if @_ == 2 && $_[0] eq $tag;
my $pa;
if ( @_ > 1 ) {
$pa = { @_ };
}
else {
$pa = shift || {};
}
# At this point, $pa can be a number (exit value), string
# (message) or hash with options.
if ( UNIVERSAL::isa($pa, 'HASH') ) {
# Get rid of -msg vs. -message ambiguity.
$pa->{-message} = $pa->{-msg};
delete($pa->{-msg});
}
elsif ( $pa =~ /^-?\d+$/ ) {
$pa = { -exitval => $pa };
}
else {
$pa = { -message => $pa };
}
# These are _our_ defaults.
$pa->{-verbose} = 0 unless exists($pa->{-verbose});
$pa->{-exitval} = 0 unless exists($pa->{-exitval});
$pa;
}
# Sneak way to know what version the user requested.
sub VERSION {
$requested_version = $_[1];
shift->SUPER::VERSION(@_);
}
package Getopt::Long::CallBack;
sub new {
my ($pkg, %atts) = @_;
bless { %atts }, $pkg;
}
sub name {
my $self = shift;
''.$self->{name};
}
use overload
# Treat this object as an ordinary string for legacy API.
'""' => \&name,
fallback => 1;
1;
################ Documentation ################
=head1 NAME
Getopt::Long - Extended processing of command line options
=head1 SYNOPSIS
use Getopt::Long;
my $data = "file.dat";
my $length = 24;
my $verbose;
GetOptions ("length=i" => \$length, # numeric
"file=s" => \$data, # string
"verbose" => \$verbose) # flag
or die("Error in command line arguments\n");
=head1 DESCRIPTION
The Getopt::Long module implements an extended getopt function called
GetOptions(). It parses the command line from C<@ARGV>, recognizing
and removing specified options and their possible values.
This function adheres to the POSIX syntax for command
line options, with GNU extensions. In general, this means that options
have long names instead of single letters, and are introduced with a
double dash "--". Support for bundling of command line options, as was
the case with the more traditional single-letter approach, is provided
but not enabled by default.
=head1 Command Line Options, an Introduction
Command line operated programs traditionally take their arguments from
the command line, for example filenames or other information that the
program needs to know. Besides arguments, these programs often take
command line I<options> as well. Options are not necessary for the
program to work, hence the name 'option', but are used to modify its
default behaviour. For example, a program could do its job quietly,
but with a suitable option it could provide verbose information about
what it did.
Command line options come in several flavours. Historically, they are
preceded by a single dash C<->, and consist of a single letter.
-l -a -c
Usually, these single-character options can be bundled:
-lac
Options can have values, the value is placed after the option
character. Sometimes with whitespace in between, sometimes not:
-s 24 -s24
Due to the very cryptic nature of these options, another style was
developed that used long names. So instead of a cryptic C<-l> one
could use the more descriptive C<--long>. To distinguish between a
bundle of single-character options and a long one, two dashes are used
to precede the option name. Early implementations of long options used
a plus C<+> instead. Also, option values could be specified either
like
--size=24
or
--size 24
The C<+> form is now obsolete and strongly deprecated.
=head1 Getting Started with Getopt::Long
Getopt::Long is the Perl5 successor of C<newgetopt.pl>. This was the
first Perl module that provided support for handling the new style of
command line options, in particular long option names, hence the Perl5
name Getopt::Long. This module also supports single-character options
and bundling.
To use Getopt::Long from a Perl program, you must include the
following line in your Perl program:
use Getopt::Long;
This will load the core of the Getopt::Long module and prepare your
program for using it. Most of the actual Getopt::Long code is not
loaded until you really call one of its functions.
In the default configuration, options names may be abbreviated to
uniqueness, case does not matter, and a single dash is sufficient,
even for long option names. Also, options may be placed between
non-option arguments. See L<Configuring Getopt::Long> for more
details on how to configure Getopt::Long.
=head2 Simple options
The most simple options are the ones that take no values. Their mere
presence on the command line enables the option. Popular examples are:
--all --verbose --quiet --debug
Handling simple options is straightforward:
my $verbose = ''; # option variable with default value (false)
my $all = ''; # option variable with default value (false)
GetOptions ('verbose' => \$verbose, 'all' => \$all);
The call to GetOptions() parses the command line arguments that are
present in C<@ARGV> and sets the option variable to the value C<1> if
the option did occur on the command line. Otherwise, the option
variable is not touched. Setting the option value to true is often
called I<enabling> the option.
The option name as specified to the GetOptions() function is called
the option I<specification>. Later we'll see that this specification
can contain more than just the option name. The reference to the
variable is called the option I<destination>.
GetOptions() will return a true value if the command line could be
processed successfully. Otherwise, it will write error messages using
die() and warn(), and return a false result.
=head2 A little bit less simple options
Getopt::Long supports two useful variants of simple options:
I<negatable> options and I<incremental> options.
A negatable option is specified with an exclamation mark C<!> after the
option name:
my $verbose = ''; # option variable with default value (false)
GetOptions ('verbose!' => \$verbose);
Now, using C<--verbose> on the command line will enable C<$verbose>,
as expected. But it is also allowed to use C<--noverbose>, which will
disable C<$verbose> by setting its value to C<0>. Using a suitable
default value, the program can find out whether C<$verbose> is false
by default, or disabled by using C<--noverbose>.
An incremental option is specified with a plus C<+> after the
option name:
my $verbose = ''; # option variable with default value (false)
GetOptions ('verbose+' => \$verbose);
Using C<--verbose> on the command line will increment the value of
C<$verbose>. This way the program can keep track of how many times the
option occurred on the command line. For example, each occurrence of
C<--verbose> could increase the verbosity level of the program.
=head2 Mixing command line option with other arguments
Usually programs take command line options as well as other arguments,
for example, file names. It is good practice to always specify the
options first, and the other arguments last. Getopt::Long will,
however, allow the options and arguments to be mixed and 'filter out'
all the options before passing the rest of the arguments to the
program. To stop Getopt::Long from processing further arguments,
insert a double dash C<--> on the command line:
--size 24 -- --all
In this example, C<--all> will I<not> be treated as an option, but
passed to the program unharmed, in C<@ARGV>.
=head2 Options with values
For options that take values it must be specified whether the option
value is required or not, and what kind of value the option expects.
Three kinds of values are supported: integer numbers, floating point
numbers, and strings.
If the option value is required, Getopt::Long will take the
command line argument that follows the option and assign this to the
option variable. If, however, the option value is specified as
optional, this will only be done if that value does not look like a
valid command line option itself.
my $tag = ''; # option variable with default value
GetOptions ('tag=s' => \$tag);
In the option specification, the option name is followed by an equals
sign C<=> and the letter C<s>. The equals sign indicates that this
option requires a value. The letter C<s> indicates that this value is
an arbitrary string. Other possible value types are C<i> for integer
values, and C<f> for floating point values. Using a colon C<:> instead
of the equals sign indicates that the option value is optional. In
this case, if no suitable value is supplied, string valued options get
an empty string C<''> assigned, while numeric options are set to C<0>.
=head2 Options with multiple values
Options sometimes take several values. For example, a program could
use multiple directories to search for library files:
--library lib/stdlib --library lib/extlib
To accomplish this behaviour, simply specify an array reference as the
destination for the option:
GetOptions ("library=s" => \@libfiles);
Alternatively, you can specify that the option can have multiple
values by adding a "@", and pass a reference to a scalar as the
destination:
GetOptions ("library=s@" => \$libfiles);
Used with the example above, C<@libfiles> c.q. C<@$libfiles> would
contain two strings upon completion: C<"lib/stdlib"> and
C<"lib/extlib">, in that order. It is also possible to specify that
only integer or floating point numbers are acceptable values.
Often it is useful to allow comma-separated lists of values as well as
multiple occurrences of the options. This is easy using Perl's split()
and join() operators:
GetOptions ("library=s" => \@libfiles);
@libfiles = split(/,/,join(',',@libfiles));
Of course, it is important to choose the right separator string for
each purpose.
Warning: What follows is an experimental feature.
Options can take multiple values at once, for example
--coordinates 52.2 16.4 --rgbcolor 255 255 149
This can be accomplished by adding a repeat specifier to the option
specification. Repeat specifiers are very similar to the C<{...}>
repeat specifiers that can be used with regular expression patterns.
For example, the above command line would be handled as follows:
GetOptions('coordinates=f{2}' => \@coor, 'rgbcolor=i{3}' => \@color);
The destination for the option must be an array or array reference.
It is also possible to specify the minimal and maximal number of
arguments an option takes. C<foo=s{2,4}> indicates an option that
takes at least two and at most 4 arguments. C<foo=s{1,}> indicates one
or more values; C<foo:s{,}> indicates zero or more option values.
=head2 Options with hash values
If the option destination is a reference to a hash, the option will
take, as value, strings of the form I<key>C<=>I<value>. The value will
be stored with the specified key in the hash.
GetOptions ("define=s" => \%defines);
Alternatively you can use:
GetOptions ("define=s%" => \$defines);
When used with command line options:
--define os=linux --define vendor=redhat
the hash C<%defines> (or C<%$defines>) will contain two keys, C<"os">
with value C<"linux"> and C<"vendor"> with value C<"redhat">. It is
also possible to specify that only integer or floating point numbers
are acceptable values. The keys are always taken to be strings.
=head2 User-defined subroutines to handle options
Ultimate control over what should be done when (actually: each time)
an option is encountered on the command line can be achieved by
designating a reference to a subroutine (or an anonymous subroutine)
as the option destination. When GetOptions() encounters the option, it
will call the subroutine with two or three arguments. The first
argument is the name of the option. (Actually, it is an object that
stringifies to the name of the option.) For a scalar or array destination,
the second argument is the value to be stored. For a hash destination,
the second argument is the key to the hash, and the third argument
the value to be stored. It is up to the subroutine to store the value,
or do whatever it thinks is appropriate.
A trivial application of this mechanism is to implement options that
are related to each other. For example:
my $verbose = ''; # option variable with default value (false)
GetOptions ('verbose' => \$verbose,
'quiet' => sub { $verbose = 0 });
Here C<--verbose> and C<--quiet> control the same variable
C<$verbose>, but with opposite values.
If the subroutine needs to signal an error, it should call die() with
the desired error message as its argument. GetOptions() will catch the
die(), issue the error message, and record that an error result must
be returned upon completion.
If the text of the error message starts with an exclamation mark C<!>
it is interpreted specially by GetOptions(). There is currently one
special command implemented: C<die("!FINISH")> will cause GetOptions()
to stop processing options, as if it encountered a double dash C<-->.
In version 2.37 the first argument to the callback function was
changed from string to object. This was done to make room for
extensions and more detailed control. The object stringifies to the
option name so this change should not introduce compatibility
problems.
Here is an example of how to access the option name and value from within
a subroutine:
GetOptions ('opt=i' => \&handler);
sub handler {
my ($opt_name, $opt_value) = @_;
print("Option name is $opt_name and value is $opt_value\n");
}
=head2 Options with multiple names
Often it is user friendly to supply alternate mnemonic names for
options. For example C<--height> could be an alternate name for
C<--length>. Alternate names can be included in the option
specification, separated by vertical bar C<|> characters. To implement
the above example:
GetOptions ('length|height=f' => \$length);
The first name is called the I<primary> name, the other names are
called I<aliases>. When using a hash to store options, the key will
always be the primary name.
Multiple alternate names are possible.
=head2 Case and abbreviations
Without additional configuration, GetOptions() will ignore the case of
option names, and allow the options to be abbreviated to uniqueness.
GetOptions ('length|height=f' => \$length, "head" => \$head);
This call will allow C<--l> and C<--L> for the length option, but
requires a least C<--hea> and C<--hei> for the head and height options.
=head2 Summary of Option Specifications
Each option specifier consists of two parts: the name specification
and the argument specification.
The name specification contains the name of the option, optionally
followed by a list of alternative names separated by vertical bar
characters.
length option name is "length"
length|size|l name is "length", aliases are "size" and "l"
The argument specification is optional. If omitted, the option is
considered boolean, a value of 1 will be assigned when the option is
used on the command line.
The argument specification can be
=over 4
=item !
The option does not take an argument and may be negated by prefixing
it with "no" or "no-". E.g. C<"foo!"> will allow C<--foo> (a value of
1 will be assigned) as well as C<--nofoo> and C<--no-foo> (a value of
0 will be assigned). If the option has aliases, this applies to the
aliases as well.
Using negation on a single letter option when bundling is in effect is
pointless and will result in a warning.
=item +
The option does not take an argument and will be incremented by 1
every time it appears on the command line. E.g. C<"more+">, when used
with C<--more --more --more>, will increment the value three times,
resulting in a value of 3 (provided it was 0 or undefined at first).
The C<+> specifier is ignored if the option destination is not a scalar.
=item = I<type> [ I<desttype> ] [ I<repeat> ]
The option requires an argument of the given type. Supported types
are:
=over 4
=item s
String. An arbitrary sequence of characters. It is valid for the
argument to start with C<-> or C<-->.
=item i
Integer. An optional leading plus or minus sign, followed by a
sequence of digits.
=item o
Extended integer, Perl style. This can be either an optional leading
plus or minus sign, followed by a sequence of digits, or an octal
string (a zero, optionally followed by '0', '1', .. '7'), or a
hexadecimal string (C<0x> followed by '0' .. '9', 'a' .. 'f', case
insensitive), or a binary string (C<0b> followed by a series of '0'
and '1').
=item f
Real number. For example C<3.14>, C<-6.23E24> and so on.
=back
The I<desttype> can be C<@> or C<%> to specify that the option is
list or a hash valued. This is only needed when the destination for
the option value is not otherwise specified. It should be omitted when
not needed.
The I<repeat> specifies the number of values this option takes per
occurrence on the command line. It has the format C<{> [ I<min> ] [ C<,> [ I<max> ] ] C<}>.
I<min> denotes the minimal number of arguments. It defaults to 1 for
options with C<=> and to 0 for options with C<:>, see below. Note that
I<min> overrules the C<=> / C<:> semantics.
I<max> denotes the maximum number of arguments. It must be at least
I<min>. If I<max> is omitted, I<but the comma is not>, there is no
upper bound to the number of argument values taken.
=item : I<type> [ I<desttype> ]
Like C<=>, but designates the argument as optional.
If omitted, an empty string will be assigned to string values options,
and the value zero to numeric options.
Note that if a string argument starts with C<-> or C<-->, it will be
considered an option on itself.
=item : I<number> [ I<desttype> ]
Like C<:i>, but if the value is omitted, the I<number> will be assigned.
=item : + [ I<desttype> ]
Like C<:i>, but if the value is omitted, the current value for the
option will be incremented.
=back
=head1 Advanced Possibilities
=head2 Object oriented interface
Getopt::Long can be used in an object oriented way as well:
use Getopt::Long;
$p = Getopt::Long::Parser->new;
$p->configure(...configuration options...);
if ($p->getoptions(...options descriptions...)) ...
if ($p->getoptionsfromarray( \@array, ...options descriptions...)) ...
Configuration options can be passed to the constructor:
$p = new Getopt::Long::Parser
config => [...configuration options...];
=head2 Thread Safety
Getopt::Long is thread safe when using ithreads as of Perl 5.8. It is
I<not> thread safe when using the older (experimental and now
obsolete) threads implementation that was added to Perl 5.005.
=head2 Documentation and help texts
Getopt::Long encourages the use of Pod::Usage to produce help
messages. For example:
use Getopt::Long;
use Pod::Usage;
my $man = 0;
my $help = 0;
GetOptions('help|?' => \$help, man => \$man) or pod2usage(2);
pod2usage(1) if $help;
pod2usage(-exitval => 0, -verbose => 2) if $man;
__END__
=head1 NAME
sample - Using Getopt::Long and Pod::Usage
=head1 SYNOPSIS
sample [options] [file ...]
Options:
-help brief help message
-man full documentation
=head1 OPTIONS
=over 8
=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 the given input file(s) and do something
useful with the contents thereof.
=cut
See L<Pod::Usage> for details.
=head2 Parsing options from an arbitrary array
By default, GetOptions parses the options that are present in the
global array C<@ARGV>. A special entry C<GetOptionsFromArray> can be
used to parse options from an arbitrary array.
use Getopt::Long qw(GetOptionsFromArray);
$ret = GetOptionsFromArray(\@myopts, ...);
When used like this, options and their possible values are removed
from C<@myopts>, the global C<@ARGV> is not touched at all.
The following two calls behave identically:
$ret = GetOptions( ... );
$ret = GetOptionsFromArray(\@ARGV, ... );
This also means that a first argument hash reference now becomes the
second argument:
$ret = GetOptions(\%opts, ... );
$ret = GetOptionsFromArray(\@ARGV, \%opts, ... );
=head2 Parsing options from an arbitrary string
A special entry C<GetOptionsFromString> can be used to parse options
from an arbitrary string.
use Getopt::Long qw(GetOptionsFromString);
$ret = GetOptionsFromString($string, ...);
The contents of the string are split into arguments using a call to
C<Text::ParseWords::shellwords>. As with C<GetOptionsFromArray>, the
global C<@ARGV> is not touched.
It is possible that, upon completion, not all arguments in the string
have been processed. C<GetOptionsFromString> will, when called in list
context, return both the return status and an array reference to any
remaining arguments:
($ret, $args) = GetOptionsFromString($string, ... );
If any arguments remain, and C<GetOptionsFromString> was not called in
list context, a message will be given and C<GetOptionsFromString> will
return failure.
As with GetOptionsFromArray, a first argument hash reference now
becomes the second argument.
=head2 Storing options values in a hash
Sometimes, for example when there are a lot of options, having a
separate variable for each of them can be cumbersome. GetOptions()
supports, as an alternative mechanism, storing options values in a
hash.
To obtain this, a reference to a hash must be passed I<as the first
argument> to GetOptions(). For each option that is specified on the
command line, the option value will be stored in the hash with the
option name as key. Options that are not actually used on the command
line will not be put in the hash, on other words,
C<exists($h{option})> (or defined()) can be used to test if an option
was used. The drawback is that warnings will be issued if the program
runs under C<use strict> and uses C<$h{option}> without testing with
exists() or defined() first.
my %h = ();
GetOptions (\%h, 'length=i'); # will store in $h{length}
For options that take list or hash values, it is necessary to indicate
this by appending an C<@> or C<%> sign after the type:
GetOptions (\%h, 'colours=s@'); # will push to @{$h{colours}}
To make things more complicated, the hash may contain references to
the actual destinations, for example:
my $len = 0;
my %h = ('length' => \$len);
GetOptions (\%h, 'length=i'); # will store in $len
This example is fully equivalent with:
my $len = 0;
GetOptions ('length=i' => \$len); # will store in $len
Any mixture is possible. For example, the most frequently used options
could be stored in variables while all other options get stored in the
hash:
my $verbose = 0; # frequently referred
my $debug = 0; # frequently referred
my %h = ('verbose' => \$verbose, 'debug' => \$debug);
GetOptions (\%h, 'verbose', 'debug', 'filter', 'size=i');
if ( $verbose ) { ... }
if ( exists $h{filter} ) { ... option 'filter' was specified ... }
=head2 Bundling
With bundling it is possible to set several single-character options
at once. For example if C<a>, C<v> and C<x> are all valid options,
-vax
will set all three.
Getopt::Long supports three styles of bundling. To enable bundling, a
call to Getopt::Long::Configure is required.
The simplest style of bundling can be enabled with:
Getopt::Long::Configure ("bundling");
Configured this way, single-character options can be bundled but long
options B<must> always start with a double dash C<--> to avoid
ambiguity. For example, when C<vax>, C<a>, C<v> and C<x> are all valid
options,
-vax
will set C<a>, C<v> and C<x>, but
--vax
will set C<vax>.
The second style of bundling lifts this restriction. It can be enabled
with:
Getopt::Long::Configure ("bundling_override");
Now, C<-vax> will set the option C<vax>.
In all of the above cases, option values may be inserted in the
bundle. For example:
-h24w80
is equivalent to
-h 24 -w 80
A third style of bundling allows only values to be bundled with
options. It can be enabled with:
Getopt::Long::Configure ("bundling_values");
Now, C<-h24> will set the option C<h> to C<24>, but option bundles
like C<-vxa> and C<-h24w80> are flagged as errors.
Enabling C<bundling_values> will disable the other two styles of
bundling.
When configured for bundling, single-character options are matched
case sensitive while long options are matched case insensitive. To
have the single-character options matched case insensitive as well,
use:
Getopt::Long::Configure ("bundling", "ignorecase_always");
It goes without saying that bundling can be quite confusing.
=head2 The lonesome dash
Normally, a lone dash C<-> on the command line will not be considered
an option. Option processing will terminate (unless "permute" is
configured) and the dash will be left in C<@ARGV>.
It is possible to get special treatment for a lone dash. This can be
achieved by adding an option specification with an empty name, for
example:
GetOptions ('' => \$stdio);
A lone dash on the command line will now be a legal option, and using
it will set variable C<$stdio>.
=head2 Argument callback
A special option 'name' C<< <> >> can be used to designate a subroutine
to handle non-option arguments. When GetOptions() encounters an
argument that does not look like an option, it will immediately call this
subroutine and passes it one parameter: the argument name. Well, actually
it is an object that stringifies to the argument name.
For example:
my $width = 80;
sub process { ... }
GetOptions ('width=i' => \$width, '<>' => \&process);
When applied to the following command line:
arg1 --width=72 arg2 --width=60 arg3
This will call
C<process("arg1")> while C<$width> is C<80>,
C<process("arg2")> while C<$width> is C<72>, and
C<process("arg3")> while C<$width> is C<60>.
This feature requires configuration option B<permute>, see section
L<Configuring Getopt::Long>.
=head1 Configuring Getopt::Long
Getopt::Long can be configured by calling subroutine
Getopt::Long::Configure(). This subroutine takes a list of quoted
strings, each specifying a configuration option to be enabled, e.g.
C<ignore_case>, or disabled, e.g. C<no_ignore_case>. Case does not
matter. Multiple calls to Configure() are possible.
Alternatively, as of version 2.24, the configuration options may be
passed together with the C<use> statement:
use Getopt::Long qw(:config no_ignore_case bundling);
The following options are available:
=over 12
=item default
This option causes all configuration options to be reset to their
default values.
=item posix_default
This option causes all configuration options to be reset to their
default values as if the environment variable POSIXLY_CORRECT had
been set.
=item auto_abbrev
Allow option names to be abbreviated to uniqueness.
Default is enabled unless environment variable
POSIXLY_CORRECT has been set, in which case C<auto_abbrev> is disabled.
=item getopt_compat
Allow C<+> to start options.
Default is enabled unless environment variable
POSIXLY_CORRECT has been set, in which case C<getopt_compat> is disabled.
=item gnu_compat
C<gnu_compat> controls whether C<--opt=> is allowed, and what it should
do. Without C<gnu_compat>, C<--opt=> gives an error. With C<gnu_compat>,
C<--opt=> will give option C<opt> and empty value.
This is the way GNU getopt_long() does it.
Note that C<--opt value> is still accepted, even though GNU
getopt_long() doesn't.
=item gnu_getopt
This is a short way of setting C<gnu_compat> C<bundling> C<permute>
C<no_getopt_compat>. With C<gnu_getopt>, command line handling should be
reasonably compatible with GNU getopt_long().
=item require_order
Whether command line arguments are allowed to be mixed with options.
Default is disabled unless environment variable
POSIXLY_CORRECT has been set, in which case C<require_order> is enabled.
See also C<permute>, which is the opposite of C<require_order>.
=item permute
Whether command line arguments are allowed to be mixed with options.
Default is enabled unless environment variable
POSIXLY_CORRECT has been set, in which case C<permute> is disabled.
Note that C<permute> is the opposite of C<require_order>.
If C<permute> is enabled, this means that
--foo arg1 --bar arg2 arg3
is equivalent to
--foo --bar arg1 arg2 arg3
If an argument callback routine is specified, C<@ARGV> will always be
empty upon successful return of GetOptions() since all options have been
processed. The only exception is when C<--> is used:
--foo arg1 --bar arg2 -- arg3
This will call the callback routine for arg1 and arg2, and then
terminate GetOptions() leaving C<"arg3"> in C<@ARGV>.
If C<require_order> is enabled, options processing
terminates when the first non-option is encountered.
--foo arg1 --bar arg2 arg3
is equivalent to
--foo -- arg1 --bar arg2 arg3
If C<pass_through> is also enabled, options processing will terminate
at the first unrecognized option, or non-option, whichever comes
first.
=item bundling (default: disabled)
Enabling this option will allow single-character options to be
bundled. To distinguish bundles from long option names, long options
I<must> be introduced with C<--> and bundles with C<->.
Note that, if you have options C<a>, C<l> and C<all>, and
auto_abbrev enabled, possible arguments and option settings are:
using argument sets option(s)
------------------------------------------
-a, --a a
-l, --l l
-al, -la, -ala, -all,... a, l
--al, --all all
The surprising part is that C<--a> sets option C<a> (due to auto
completion), not C<all>.
Note: disabling C<bundling> also disables C<bundling_override>.
=item bundling_override (default: disabled)
If C<bundling_override> is enabled, bundling is enabled as with
C<bundling> but now long option names override option bundles.
Note: disabling C<bundling_override> also disables C<bundling>.
B<Note:> Using option bundling can easily lead to unexpected results,
especially when mixing long options and bundles. Caveat emptor.
=item ignore_case (default: enabled)
If enabled, case is ignored when matching option names. If, however,
bundling is enabled as well, single character options will be treated
case-sensitive.
With C<ignore_case>, option specifications for options that only
differ in case, e.g., C<"foo"> and C<"Foo">, will be flagged as
duplicates.
Note: disabling C<ignore_case> also disables C<ignore_case_always>.
=item ignore_case_always (default: disabled)
When bundling is in effect, case is ignored on single-character
options also.
Note: disabling C<ignore_case_always> also disables C<ignore_case>.
=item auto_version (default:disabled)
Automatically provide support for the B<--version> option if
the application did not specify a handler for this option itself.
Getopt::Long will provide a standard version message that includes the
program name, its version (if $main::VERSION is defined), and the
versions of Getopt::Long and Perl. The message will be written to
standard output and processing will terminate.
C<auto_version> will be enabled if the calling program explicitly
specified a version number higher than 2.32 in the C<use> or
C<require> statement.
=item auto_help (default:disabled)
Automatically provide support for the B<--help> and B<-?> options if
the application did not specify a handler for this option itself.
Getopt::Long will provide a help message using module L<Pod::Usage>. The
message, derived from the SYNOPSIS POD section, will be written to
standard output and processing will terminate.
C<auto_help> will be enabled if the calling program explicitly
specified a version number higher than 2.32 in the C<use> or
C<require> statement.
=item pass_through (default: disabled)
With C<pass_through> anything that is unknown, ambiguous or supplied with
an invalid option will not be flagged as an error. Instead the unknown
option(s) will be passed to the catchall C<< <> >> if present, otherwise
through to C<@ARGV>. This makes it possible to write wrapper scripts that
process only part of the user supplied command line arguments, and pass the
remaining options to some other program.
If C<require_order> is enabled, options processing will terminate at the
first unrecognized option, or non-option, whichever comes first and all
remaining arguments are passed to C<@ARGV> instead of the catchall
C<< <> >> if present. However, if C<permute> is enabled instead, results
can become confusing.
Note that the options terminator (default C<-->), if present, will
also be passed through in C<@ARGV>.
=item prefix
The string that starts options. If a constant string is not
sufficient, see C<prefix_pattern>.
=item prefix_pattern
A Perl pattern that identifies the strings that introduce options.
Default is C<--|-|\+> unless environment variable
POSIXLY_CORRECT has been set, in which case it is C<--|->.
=item long_prefix_pattern
A Perl pattern that allows the disambiguation of long and short
prefixes. Default is C<-->.
Typically you only need to set this if you are using nonstandard
prefixes and want some or all of them to have the same semantics as
'--' does under normal circumstances.
For example, setting prefix_pattern to C<--|-|\+|\/> and
long_prefix_pattern to C<--|\/> would add Win32 style argument
handling.
=item debug (default: disabled)
Enable debugging output.
=back
=head1 Exportable Methods
=over
=item VersionMessage
This subroutine provides a standard version message. Its argument can be:
=over 4
=item *
A string containing the text of a message to print I<before> printing
the standard message.
=item *
A numeric value corresponding to the desired exit status.
=item *
A reference to a hash.
=back
If more than one argument is given then the entire argument list is
assumed to be a hash. If a hash is supplied (either as a reference or
as a list) it should contain one or more elements with the following
keys:
=over 4
=item C<-message>
=item C<-msg>
The text of a message to print immediately prior to printing the
program's usage message.
=item C<-exitval>
The desired exit status to pass to the B<exit()> function.
This should be an integer, or else the string "NOEXIT" to
indicate that control should simply be returned without
terminating the invoking process.
=item C<-output>
A reference to a filehandle, or the pathname of a file to which the
usage message should be written. The default is C<\*STDERR> unless the
exit value is less than 2 (in which case the default is C<\*STDOUT>).
=back
You cannot tie this routine directly to an option, e.g.:
GetOptions("version" => \&VersionMessage);
Use this instead:
GetOptions("version" => sub { VersionMessage() });
=item HelpMessage
This subroutine produces a standard help message, derived from the
program's POD section SYNOPSIS using L<Pod::Usage>. It takes the same
arguments as VersionMessage(). In particular, you cannot tie it
directly to an option, e.g.:
GetOptions("help" => \&HelpMessage);
Use this instead:
GetOptions("help" => sub { HelpMessage() });
=back
=head1 Return values and Errors
Configuration errors and errors in the option definitions are
signalled using die() and will terminate the calling program unless
the call to Getopt::Long::GetOptions() was embedded in C<eval { ...
}>, or die() was trapped using C<$SIG{__DIE__}>.
GetOptions returns true to indicate success.
It returns false when the function detected one or more errors during
option parsing. These errors are signalled using warn() and can be
trapped with C<$SIG{__WARN__}>.
=head1 Legacy
The earliest development of C<newgetopt.pl> started in 1990, with Perl
version 4. As a result, its development, and the development of
Getopt::Long, has gone through several stages. Since backward
compatibility has always been extremely important, the current version
of Getopt::Long still supports a lot of constructs that nowadays are
no longer necessary or otherwise unwanted. This section describes
briefly some of these 'features'.
=head2 Default destinations
When no destination is specified for an option, GetOptions will store
the resultant value in a global variable named C<opt_>I<XXX>, where
I<XXX> is the primary name of this option. When a program executes
under C<use strict> (recommended), these variables must be
pre-declared with our() or C<use vars>.
our $opt_length = 0;
GetOptions ('length=i'); # will store in $opt_length
To yield a usable Perl variable, characters that are not part of the
syntax for variables are translated to underscores. For example,
C<--fpp-struct-return> will set the variable
C<$opt_fpp_struct_return>. Note that this variable resides in the
namespace of the calling program, not necessarily C<main>. For
example:
GetOptions ("size=i", "sizes=i@");
with command line "-size 10 -sizes 24 -sizes 48" will perform the
equivalent of the assignments
$opt_size = 10;
@opt_sizes = (24, 48);
=head2 Alternative option starters
A string of alternative option starter characters may be passed as the
first argument (or the first argument after a leading hash reference
argument).
my $len = 0;
GetOptions ('/', 'length=i' => $len);
Now the command line may look like:
/length 24 -- arg
Note that to terminate options processing still requires a double dash
C<-->.
GetOptions() will not interpret a leading C<< "<>" >> as option starters
if the next argument is a reference. To force C<< "<" >> and C<< ">" >> as
option starters, use C<< "><" >>. Confusing? Well, B<using a starter
argument is strongly deprecated> anyway.
=head2 Configuration variables
Previous versions of Getopt::Long used variables for the purpose of
configuring. Although manipulating these variables still work, it is
strongly encouraged to use the C<Configure> routine that was introduced
in version 2.17. Besides, it is much easier.
=head1 Tips and Techniques
=head2 Pushing multiple values in a hash option
Sometimes you want to combine the best of hashes and arrays. For
example, the command line:
--list add=first --list add=second --list add=third
where each successive 'list add' option will push the value of add
into array ref $list->{'add'}. The result would be like
$list->{add} = [qw(first second third)];
This can be accomplished with a destination routine:
GetOptions('list=s%' =>
sub { push(@{$list{$_[1]}}, $_[2]) });
=head1 Troubleshooting
=head2 GetOptions does not return a false result when an option is not supplied
That's why they're called 'options'.
=head2 GetOptions does not split the command line correctly
The command line is not split by GetOptions, but by the command line
interpreter (CLI). On Unix, this is the shell. On Windows, it is
COMMAND.COM or CMD.EXE. Other operating systems have other CLIs.
It is important to know that these CLIs may behave different when the
command line contains special characters, in particular quotes or
backslashes. For example, with Unix shells you can use single quotes
(C<'>) and double quotes (C<">) to group words together. The following
alternatives are equivalent on Unix:
"two words"
'two words'
two\ words
In case of doubt, insert the following statement in front of your Perl
program:
print STDERR (join("|",@ARGV),"\n");
to verify how your CLI passes the arguments to the program.
=head2 Undefined subroutine &main::GetOptions called
Are you running Windows, and did you write
use GetOpt::Long;
(note the capital 'O')?
=head2 How do I put a "-?" option into a Getopt::Long?
You can only obtain this using an alias, and Getopt::Long of at least
version 2.13.
use Getopt::Long;
GetOptions ("help|?"); # -help and -? will both set $opt_help
Other characters that can't appear in Perl identifiers are also supported
as aliases with Getopt::Long of at least version 2.39.
As of version 2.32 Getopt::Long provides auto-help, a quick and easy way
to add the options --help and -? to your program, and handle them.
See C<auto_help> in section L<Configuring Getopt::Long>.
=head1 AUTHOR
Johan Vromans <jvromans@squirrel.nl>
=head1 COPYRIGHT AND DISCLAIMER
This program is Copyright 1990,2015 by Johan Vromans.
This program is free software; you can redistribute it and/or
modify it under the terms of the Perl Artistic License or the
GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
If you do not have a copy of the GNU General Public License write to
the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
MA 02139, USA.
=cut
| operepo/ope | client_tools/svc/rc/usr/share/perl5/core_perl/Getopt/Long.pm | Perl | mit | 83,186 |
#TODO: Write the general version, using the work done on the GeneTrack build method
use 5.10.0;
use strict;
use warnings;
package Seq::Tracks::Region::Build;
use Mouse 2;
our $VERSION = '0.001';
#Finish if needed
__PACKAGE__->meta->make_immutable;
1;
| akotlar/bystro | lib/Seq/Tracks/Region/Build.pm | Perl | apache-2.0 | 257 |
# <@LICENSE>
# 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.
# </@LICENSE>
=head1 NAME
Mail::SpamAssassin::AutoWhitelist - auto-whitelist handler for SpamAssassin
=head1 SYNOPSIS
(see Mail::SpamAssassin)
=head1 DESCRIPTION
Mail::SpamAssassin is a module to identify spam using text analysis and
several internet-based realtime blacklists.
This class is used internally by SpamAssassin to manage the automatic
whitelisting functionality. Please refer to the C<Mail::SpamAssassin>
documentation for public interfaces.
=head1 METHODS
=over 4
=cut
package Mail::SpamAssassin::AutoWhitelist;
use strict;
use warnings;
# use bytes;
use re 'taint';
use NetAddr::IP 4.000;
use Mail::SpamAssassin;
use Mail::SpamAssassin::Logger;
use Mail::SpamAssassin::Util qw(untaint_var);
our @ISA = qw();
###########################################################################
sub new {
my $class = shift;
$class = ref($class) || $class;
my ($main, $msg) = @_;
my $conf = $main->{conf};
my $self = {
main => $main,
factor => $conf->{auto_whitelist_factor},
ipv4_mask_len => $conf->{auto_whitelist_ipv4_mask_len},
ipv6_mask_len => $conf->{auto_whitelist_ipv6_mask_len},
};
my $factory;
if ($main->{pers_addr_list_factory}) {
$factory = $main->{pers_addr_list_factory};
}
else {
my $type = $conf->{auto_whitelist_factory};
if ($type =~ /^([_A-Za-z0-9:]+)$/) {
$type = untaint_var($type);
eval '
require '.$type.';
$factory = '.$type.'->new();
1;
' or do {
my $eval_stat = $@ ne '' ? $@ : "errno=$!"; chomp $eval_stat;
warn "auto-whitelist: $eval_stat\n";
undef $factory;
};
$main->set_persistent_address_list_factory($factory) if $factory;
}
else {
warn "auto-whitelist: illegal auto_whitelist_factory setting\n";
}
}
if (!defined $factory) {
$self->{checker} = undef;
} else {
$self->{checker} = $factory->new_checker($self->{main});
}
bless ($self, $class);
$self;
}
###########################################################################
=item $meanscore = awl->check_address($addr, $originating_ip, $signedby);
This method will return the mean score of all messages associated with the
given address, or undef if the address hasn't been seen before.
If B<$originating_ip> is supplied, it will be used in the lookup.
=cut
sub check_address {
my ($self, $addr, $origip, $signedby) = @_;
if (!defined $self->{checker}) {
return; # no factory defined; we can't check
}
$self->{entry} = undef;
my $fulladdr = $self->pack_addr ($addr, $origip);
my $entry = $self->{checker}->get_addr_entry ($fulladdr, $signedby);
$self->{entry} = $entry;
if (!$entry->{msgcount}) {
# no entry found
if (defined $origip) {
# try upgrading a default entry (probably from "add-addr-to-foo")
my $noipaddr = $self->pack_addr ($addr, undef);
my $noipent = $self->{checker}->get_addr_entry ($noipaddr, undef);
if (defined $noipent->{msgcount} && $noipent->{msgcount} > 0) {
dbg("auto-whitelist: found entry w/o IP address for $addr: replacing with $origip");
$self->{checker}->remove_entry($noipent);
# Now assign proper entry the count and totscore values of the
# no-IP entry instead of assigning the whole value to avoid
# wiping out any information added to the previous entry.
$entry->{msgcount} = $noipent->{msgcount};
$entry->{totscore} = $noipent->{totscore};
}
}
}
if ($entry->{msgcount} < 0 ||
$entry->{msgcount} != $entry->{msgcount} || # test for NaN
$entry->{totscore} != $entry->{totscore})
{
warn "auto-whitelist: resetting bad data for ($addr, $origip), ".
"count: $entry->{msgcount}, totscore: $entry->{totscore}\n";
$entry->{msgcount} = $entry->{totscore} = 0;
}
return !$entry->{msgcount} ? undef : $entry->{totscore} / $entry->{msgcount};
}
###########################################################################
=item awl->count();
This method will return the count of messages used in determining the
whitelist correction.
=cut
sub count {
my $self = shift;
return $self->{entry}->{msgcount};
}
###########################################################################
=item awl->add_score($score);
This method will add half the score to the current entry. Half the
score is used, so that repeated use of the same From and IP address
combination will gradually reduce the score.
=cut
sub add_score {
my ($self,$score) = @_;
if (!defined $self->{checker}) {
return; # no factory defined; we can't check
}
if ($score != $score) {
warn "auto-whitelist: attempt to add a $score to AWL entry ignored\n";
return; # don't try to add a NaN
}
$self->{entry}->{msgcount} ||= 0;
$self->{checker}->add_score($self->{entry}, $score);
}
###########################################################################
=item awl->add_known_good_address($addr);
This method will add a score of -100 to the given address -- effectively
"bootstrapping" the address as being one that should be whitelisted.
=cut
sub add_known_good_address {
my ($self, $addr, $signedby) = @_;
return $self->modify_address($addr, -100, $signedby);
}
###########################################################################
=item awl->add_known_bad_address($addr);
This method will add a score of 100 to the given address -- effectively
"bootstrapping" the address as being one that should be blacklisted.
=cut
sub add_known_bad_address {
my ($self, $addr, $signedby) = @_;
return $self->modify_address($addr, 100, $signedby);
}
###########################################################################
sub remove_address {
my ($self, $addr, $signedby) = @_;
return $self->modify_address($addr, undef, $signedby);
}
###########################################################################
sub modify_address {
my ($self, $addr, $score, $signedby) = @_;
if (!defined $self->{checker}) {
return; # no factory defined; we can't check
}
my $fulladdr = $self->pack_addr ($addr, undef);
my $entry = $self->{checker}->get_addr_entry ($fulladdr, $signedby);
# remove any old entries (will remove per-ip entries as well)
# always call this regardless, as the current entry may have 0
# scores, but the per-ip one may have more
$self->{checker}->remove_entry($entry);
# remove address only, no new score to add
if (!defined $score) { return 1; }
if ($score != $score) { return 1; } # don't try to add a NaN
# else add score. get a new entry first
$entry = $self->{checker}->get_addr_entry ($fulladdr, $signedby);
$self->{checker}->add_score($entry, $score);
return 1;
}
###########################################################################
sub finish {
my $self = shift;
return if !defined $self->{checker};
$self->{checker}->finish();
}
###########################################################################
sub ip_to_awl_key {
my ($self, $origip) = @_;
my $result;
local $1;
if (!defined $origip) {
# could not find an IP address to use
} elsif ($origip =~ /^ (\d{1,3} \. \d{1,3}) \. \d{1,3} \. \d{1,3} $/xs) {
my $mask_len = $self->{ipv4_mask_len};
$mask_len = 16 if !defined $mask_len;
# handle the default and easy cases manually
if ($mask_len == 32) {
$result = $origip;
} elsif ($mask_len == 16) {
$result = $1;
} else {
my $origip_obj = NetAddr::IP->new($origip . '/' . $mask_len);
if (!defined $origip_obj) { # invalid IPv4 address
dbg("auto-whitelist: bad IPv4 address $origip");
} else {
$result = $origip_obj->network->addr;
$result =~s/(\.0){1,3}\z//; # truncate zero tail
}
}
} elsif (index($origip, ':') >= 0 && # triage
$origip =~
/^ [0-9a-f]{0,4} (?: : [0-9a-f]{0,4} | \. [0-9]{1,3} ){2,9} $/xsi) {
# looks like an IPv6 address
my $mask_len = $self->{ipv6_mask_len};
$mask_len = 48 if !defined $mask_len;
my $origip_obj = NetAddr::IP->new6($origip . '/' . $mask_len);
if (!defined $origip_obj) { # invalid IPv6 address
dbg("auto-whitelist: bad IPv6 address $origip");
} elsif (NetAddr::IP->can('full6')) { # since NetAddr::IP 4.010
$result = $origip_obj->network->full6; # string in a canonical form
$result =~ s/(:0000){1,7}\z/::/; # compress zero tail
}
} else {
dbg("auto-whitelist: bad IP address $origip");
}
if (defined $result && length($result) > 39) { # just in case, keep under
$result = substr($result,0,39); # the awl.ip field size
}
if (defined $result) {
dbg("auto-whitelist: IP masking %s -> %s", $origip,$result);
}
return $result;
}
###########################################################################
sub pack_addr {
my ($self, $addr, $origip) = @_;
$addr = lc $addr;
$addr =~ s/[\000\;\'\"\!\|]/_/gs; # paranoia
if (defined $origip) {
$origip = $self->ip_to_awl_key($origip);
}
if (!defined $origip) {
# could not find an IP address to use, could be localhost mail
# or from the user running "add-addr-to-*".
$origip = 'none';
}
return $addr . "|ip=" . $origip;
}
###########################################################################
1;
=back
=cut
| apache/spamassassin | lib/Mail/SpamAssassin/AutoWhitelist.pm | Perl | apache-2.0 | 10,113 |
package DDG::Goodie::IsAwesome::Marneus68;
# ABSTRACT: Marneus68's first Goodie
use DDG::Goodie;
zci answer_type => "is_awesome_marneus68";
zci is_cached => 1;
name "IsAwesome Marneus68";
description "My first Goodie, it let's the world know that GitHubUsername is awesome";
primary_example_queries "duckduckhack Marneus68";
category "special";
topics "special_interest", "geek";
code_url "https://github.com/duckduckgo/zeroclickinfo-goodies/blob/master/lib/DDG/Goodie/IsAwesome/Marneus68.pm";
attribution github => ["Marneus68", "Duane Bekaert"];
triggers start => "duckduckhack marneus68";
handle remainder => sub {
return if $_;
return "Marneus68 is awesome and has successfully completed the DuckDuckHack Goodie tutorial!";
};
1;
| Acidburn0zzz/zeroclickinfo-goodies | lib/DDG/Goodie/IsAwesome/Marneus68.pm | Perl | apache-2.0 | 750 |
package Google::Ads::AdWords::v201406::UserListLogicalRule;
use strict;
use warnings;
__PACKAGE__->_set_element_form_qualified(1);
sub get_xmlns { 'https://adwords.google.com/api/adwords/rm/v201406' };
our $XML_ATTRIBUTE_CLASS;
undef $XML_ATTRIBUTE_CLASS;
sub __get_attr_class {
return $XML_ATTRIBUTE_CLASS;
}
use Class::Std::Fast::Storable constructor => 'none';
use base qw(Google::Ads::SOAP::Typelib::ComplexType);
{ # BLOCK to scope variables
my %operator_of :ATTR(:get<operator>);
my %ruleOperands_of :ATTR(:get<ruleOperands>);
__PACKAGE__->_factory(
[ qw( operator
ruleOperands
) ],
{
'operator' => \%operator_of,
'ruleOperands' => \%ruleOperands_of,
},
{
'operator' => 'Google::Ads::AdWords::v201406::UserListLogicalRule::Operator',
'ruleOperands' => 'Google::Ads::AdWords::v201406::LogicalUserListOperand',
},
{
'operator' => 'operator',
'ruleOperands' => 'ruleOperands',
}
);
} # end BLOCK
1;
=pod
=head1 NAME
Google::Ads::AdWords::v201406::UserListLogicalRule
=head1 DESCRIPTION
Perl data type class for the XML Schema defined complexType
UserListLogicalRule from the namespace https://adwords.google.com/api/adwords/rm/v201406.
A user list logical rule. A rule has a logical operator (and/or/not) and a list of operands that can be user lists or user interests.
=head2 PROPERTIES
The following properties may be accessed using get_PROPERTY / set_PROPERTY
methods:
=over
=item * operator
=item * ruleOperands
=back
=head1 METHODS
=head2 new
Constructor. The following data structure may be passed to new():
=head1 AUTHOR
Generated by SOAP::WSDL
=cut
| gitpan/GOOGLE-ADWORDS-PERL-CLIENT | lib/Google/Ads/AdWords/v201406/UserListLogicalRule.pm | Perl | apache-2.0 | 1,712 |
#
# Copyright 2017 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package storage::storagetek::sl::snmp::mode::components::elevator;
use strict;
use warnings;
use storage::storagetek::sl::snmp::mode::components::resources qw($map_status);
my $mapping = {
slElevatorSerialNum => { oid => '.1.3.6.1.4.1.1211.1.15.4.12.1.5' },
slElevatorStatusEnum => { oid => '.1.3.6.1.4.1.1211.1.15.4.12.1.8', map => $map_status },
};
my $oid_slElevatorEntry = '.1.3.6.1.4.1.1211.1.15.4.12.1';
sub load {
my ($self) = @_;
push @{$self->{request}}, { oid => $oid_slElevatorEntry };
}
sub check {
my ($self) = @_;
$self->{output}->output_add(long_msg => "Checking elevators");
$self->{components}->{elevator} = {name => 'elevators', total => 0, skip => 0};
return if ($self->check_filter(section => 'elevator'));
foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{results}->{$oid_slElevatorEntry}})) {
next if ($oid !~ /^$mapping->{slElevatorStatusEnum}->{oid}\.(.*)$/);
my $instance = $1;
my $result = $self->{snmp}->map_instance(mapping => $mapping, results => $self->{results}->{$oid_slElevatorEntry}, instance => $instance);
next if ($self->check_filter(section => 'elevator', instance => $instance));
$self->{components}->{elevator}->{total}++;
$self->{output}->output_add(long_msg => sprintf("elevator '%s' status is '%s' [instance: %s].",
$result->{slElevatorSerialNum}, $result->{slElevatorStatusEnum},
$instance
));
my $exit = $self->get_severity(label => 'status', section => 'elevator', value => $result->{slElevatorStatusEnum});
if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) {
$self->{output}->output_add(severity => $exit,
short_msg => sprintf("Elevator '%s' status is '%s'",
$result->{slElevatorSerialNum}, $result->{slElevatorStatusEnum}));
}
}
}
1; | maksimatveev/centreon-plugins | storage/storagetek/sl/snmp/mode/components/elevator.pm | Perl | apache-2.0 | 2,841 |
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
=head1 NAME
Bio::EnsEMBL::Compara::Graph::Node
=head1 DESCRIPTION
Object oriented graph system which is based on Node and Link objects. There is
no 'graph' object, the graph is constructed out of Nodes and Links, and the
graph is 'walked' from Node to Link to Node. Can be used to represent any graph
structure from DAGs (directed acyclic graph) to Trees to undirected cyclic Graphs.
The system is fully connected so from any object in the graph one can 'walk' to
any other. Links contain pointers to the nodes on either side (called neighbors),
and each Node contains a list of the links it is connected to.
Nodes also keep hashes of their neighbors for fast 'set theory' operations.
This graph system is used as the foundation for the Nested-set
(Compara::NestedSet) system for storing trees in the compara database.
System has a simple API based on creating Nodes and then linking them together:
my $node1 = new Bio::EnsEMBL::Compara::Graph::Node;
my $node2 = new Bio::EnsEMBL::Compara::Graph::Node;
new Bio::EnsEMBL::Compara::Graph::Link($node1, $node2, $distance_between);
And to 'disconnect' nodes, one just breaks a link;
my $link = $node1->link_for_neighbor($node2);
$link->dealloc;
Convenience methods to simplify this process
$node1->create_link_to_node($node2, $distance_between);
$node2->unlink_neighbor($node1);
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
=head1 APPENDIX
The rest of the documentation details each of the object methods. Internal methods are usually preceded with a _
=cut
package Bio::EnsEMBL::Compara::Graph::Node;
use strict;
use warnings;
use Bio::EnsEMBL::Utils::Exception;
use Bio::EnsEMBL::Utils::Argument;
use Bio::EnsEMBL::Utils::Scalar qw(:assert);
use Bio::EnsEMBL::Compara::Graph::Link;
use base ('Bio::EnsEMBL::Compara::Taggable');
#################################################
# creation methods
#################################################
sub new {
my ($class, @args) = @_;
## Allows to create a new object from an existing one with $object->new
$class = ref($class) if (ref($class));
my $self = {};
bless $self,$class;
$self->{'_node_id'} = undef;
return $self;
}
sub copy {
my $self = shift;
my $mycopy = @_ ? shift : {};
bless $mycopy, ref($self);
$mycopy->{'_node_id'} = undef;
if($self->{'_tags'}) {
%{$mycopy->{'_tags'}} = %{$self->{'_tags'}};
}
return $mycopy;
}
sub copy_shallow_links {
my $self = shift;
my $mycopy = $self->copy;
#copies links to all my neighbors but does not recurse beyond
foreach my $link (@{$self->links}) {
$mycopy->create_link_to_node($link->get_neighbor($self),
$link->distance_between);
}
return $mycopy;
}
sub copy_graph {
my $self = shift;
my $incoming_link = shift;
my $mycopy = $self->copy;
#printf("Graph::Node::copy %d", $self);
#printf(" from link %s", $incoming_link) if($incoming_link);
#print("\n");
foreach my $link (@{$self->links}) {
next if($incoming_link and $link->equals($incoming_link));
my $newnode = $link->get_neighbor($self)->copy_graph($link);
$mycopy->create_link_to_node($newnode, $link->distance_between);
}
return $mycopy;
}
#################################################
#
# get/set variable methods
#
#################################################
=head2 node_id
Arg [1] : (opt.) integer node_id
Example : my $nsetID = $object->node_id();
Example : $object->node_id(12);
Description: Getter/Setter for the node_id of this object in the database
Returntype : integer node_id
Exceptions : none
Caller : general
=cut
sub node_id {
my $self = shift;
$self->{'_node_id'} = shift if(@_);
return $self unless(defined($self->{'_node_id'}));
return $self->{'_node_id'};
}
sub name {
my $self = shift;
my $value = shift;
if(defined($value)) { $self->add_tag('name', $value); }
else { $value = $self->get_tagvalue('name'); }
return $value;
}
#######################################
# Set manipulation methods
#######################################
=head2 create_link_to_node
Overview : attaches neighbor Graph::Node to this nested set
Arg [1] : Bio::EnsEMBL::Compara::Graph::Node $node
Arg [2] : (opt.) <float> distance to node
Example : $self->add_child($node);
Returntype : Compara::Graph::Link object
Exceptions : if neighbor is undef or not a NestedSet subclass
Caller : general
=cut
sub create_link_to_node {
my $self = shift;
my $node = shift;
my $distance = shift;
assert_ref($node, 'Bio::EnsEMBL::Compara::Graph::Node');
#print("create_link_to_node\n"); $self->print_node; $node->print_node;
my $link = $self->link_for_neighbor($node);
return $link if($link);
#results in calls to _add_neighbor_link_to_hash on each node
$link = new Bio::EnsEMBL::Compara::Graph::Link($self, $node);
if(defined($distance)) {
$link->distance_between($distance);
}
return $link;
}
sub create_directed_link_to_node {
my $self = shift;
my $node = shift;
my $distance = shift;
assert_ref($node, 'Bio::EnsEMBL::Compara::Graph::Node');
#print("create_link_to_node\n"); $self->print_node; $node->print_node;
my $link = $self->link_for_neighbor($node);
return $link if($link);
#results in calls to _add_neighbor_link_to_hash on each node
$link = new Bio::EnsEMBL::Compara::Graph::Link($self, $node);
if(defined($distance)) {
$link->distance_between($distance);
}
$link->{'_link_node2'}->_unlink_node_in_hash($link->{'_link_node1'});
return $link;
}
#
# internal method called by Compara::Graph::Link
sub _add_neighbor_link_to_hash {
my $self = shift;
my $neighbor = shift;
my $link = shift;
$self->{'_obj_id_to_link'} = {} unless($self->{'_obj_id_to_link'});
$self->{'_obj_id_to_link'}->{$neighbor} = $link;
}
sub _unlink_node_in_hash {
my $self = shift;
my $neighbor = shift;
delete $self->{'_obj_id_to_link'}->{$neighbor};
}
=head2 unlink_neighbor
Overview : unlink and release neighbor from self if its mine
Arg [1] : $node Bio::EnsEMBL::Compara::Graph::Node instance
Example : $self->unlink_neighbor($node);
Returntype : undef
Caller : general
=cut
sub unlink_neighbor {
my ($self, $node) = @_;
assert_ref($node, 'Bio::EnsEMBL::Compara::Graph::Node');
my $link = $self->link_for_neighbor($node);
throw("$self not my neighbor $node") unless($link);
$link->dealloc;
return undef;
}
sub unlink_all {
my $self = shift;
foreach my $link (@{$self->links}) {
$link->dealloc;
}
return undef;
}
=head2 cascade_unlink
Overview : release all neighbors and clear arrays and hashes
Example : $self->cascade_unlink
Returntype : $self
Exceptions : none
Caller : general
=cut
sub cascade_unlink {
my $self = shift;
my $caller = shift;
no warnings qw/recursion/;
#printf("cascade_unlink : "); $self->print_node;
my @neighbors;
foreach my $link (@{$self->links}) {
my $neighbor = $link->get_neighbor($self);
next if($caller and $neighbor->equals($caller));
$link->dealloc;
push @neighbors, $neighbor;
}
foreach my $neighbor (@neighbors) {
$neighbor->cascade_unlink($self);
}
return $self;
}
sub minimize_node {
my $self = shift;
return $self unless($self->link_count() == 2);
#printf("Node::minimize_node "); $self->print_node;
my ($link1, $link2) = @{$self->links};
my $dist = $link1->distance_between + $link2->distance_between;
my $node1 = $link1->get_neighbor($self);
my $node2 = $link2->get_neighbor($self);
new Bio::EnsEMBL::Compara::Graph::Link($node1, $node2, $dist);
$link1->dealloc;
$link2->dealloc;
return undef;
}
=head2 links
Overview : returns a list of Compara::Graph::Link connected to this node
Example : my @links = @{self->links()};
Returntype : array reference of Bio::EnsEMBL::Compara::Graph::Link objects (could be empty)
Exceptions : none
Caller : general
=cut
sub links {
my $self = shift;
return [] unless($self->{'_obj_id_to_link'});
my @links = values(%{$self->{'_obj_id_to_link'}});
return \@links;
}
sub link_for_neighbor {
my $self = shift;
my $node = shift;
assert_ref($node, 'Bio::EnsEMBL::Compara::Graph::Node');
return $self->{'_obj_id_to_link'}->{$node};
}
sub print_node {
my $self = shift;
printf("Node(%s)%s\n", $self, $self->name);
}
sub print_links {
my $self = shift;
foreach my $link (@{$self->links}) {
$link->print_link;
}
}
sub link_count {
my $self = shift;
return scalar(@{$self->links});
}
sub is_leaf {
my $self = shift;
return 1 if($self->link_count <= 1);
return 0;
}
##################################
#
# simple search methods
#
##################################
sub equals {
my $self = shift;
my $other = shift;
#throw("arg must be a [Bio::EnsEMBL::Compara::Graph::Node] not a [$other]")
# unless($other and $other->isa('Bio::EnsEMBL::Compara::Graph::Node'));
return 1 if($self eq $other);
return 0;
}
sub like {
my $self = shift;
my $other = shift;
assert_ref($other, 'Bio::EnsEMBL::Compara::Graph::Node');
return 1 if($self eq $other);
return 0 unless($self->link_count == $other->link_count);
foreach my $link (@{$self->links}) {
my $node = $link->get_neighbor($self);
return 0 unless($other->has_neighbor($node));
}
return 1;
}
sub has_neighbor {
my $self = shift;
my $node = shift;
assert_ref($node, 'Bio::EnsEMBL::Compara::Graph::Node');
return 1 if(defined($self->{'_obj_id_to_link'}->{$node}));
return 0;
}
sub neighbors {
my $self = shift;
my @neighbors;
foreach my $link (@{$self->links}) {
my $neighbor = $link->get_neighbor($self);
push @neighbors, $neighbor;
}
return \@neighbors;
}
sub find_node_by_name {
my $self = shift;
my $name = shift;
unless (defined $name) {
throw("a name needs to be given as argument. The argument is currently undef\n");
}
return $self if($name eq $self->name);
foreach my $neighbor (@{$self->_walk_graph_until(-name => $name)}) {
return $neighbor if($name eq $neighbor->name);
}
return undef;
}
sub find_node_by_node_id {
my $self = shift;
my $node_id = shift;
unless (defined $node_id) {
throw("a node_id needs to be given as argument. The argument is currently undef\n");
}
return $self if($node_id eq $self->node_id);
foreach my $neighbor (@{$self->_walk_graph_until(-node_id => $node_id)}) {
return $neighbor if($node_id eq $neighbor->node_id);
}
return undef;
}
sub all_nodes_in_graph {
my $self = shift;
return $self->_walk_graph_until;
}
sub all_links_in_graph {
my ($self, @args) = @_;
my $cache_links;
if (scalar @args) {
($cache_links) =
rearrange([qw(CACHE_LINKS)], @args);
}
no warnings qw/recursion/;
unless (defined $cache_links) {
$cache_links = {};
}
foreach my $link (@{$self->links}) {
next if ($cache_links->{$link});
$cache_links->{$link} = $link;
my $neighbor = $link->get_neighbor($self);
$neighbor->all_links_in_graph(-cache_links => $cache_links);
}
return [ values %{$cache_links} ];
}
sub _walk_graph_until {
my ($self, @args) = @_;
my $name;
my $node_id;
my $cache_nodes;
if (scalar @args) {
($name, $node_id, $cache_nodes) =
rearrange([qw(NAME NODE_ID CACHE_NODES)], @args);
}
no warnings qw/recursion/;
unless (defined $cache_nodes) {
$cache_nodes = {};
$cache_nodes->{$self} = $self;
}
foreach my $neighbor (@{$self->neighbors}) {
next if ($cache_nodes->{$neighbor});
$cache_nodes->{$neighbor} = $neighbor;
last if (defined $name && $name eq $neighbor->name);
last if (defined $node_id && $node_id eq $neighbor->node_id);
$neighbor->_walk_graph_until(-name => $name, -node_id => $node_id, -cache_nodes => $cache_nodes);
}
return [ values %{$cache_nodes} ];
}
1;
| ckongEbi/ensembl-compara | modules/Bio/EnsEMBL/Compara/Graph/Node.pm | Perl | apache-2.0 | 12,822 |
package TAP::Parser::SourceHandler;
use strict;
use vars qw($VERSION @ISA);
use TAP::Object ();
use TAP::Parser::Iterator ();
@ISA = qw(TAP::Object);
=head1 NAME
TAP::Parser::SourceHandler - Base class for different TAP source handlers
=head1 VERSION
Version 3.26
=cut
$VERSION = '3.26';
=head1 SYNOPSIS
# abstract class - don't use directly!
# see TAP::Parser::IteratorFactory for general usage
# must be sub-classed for use
package MySourceHandler;
use base qw( TAP::Parser::SourceHandler );
sub can_handle { return $confidence_level }
sub make_iterator { return $iterator }
# see example below for more details
=head1 DESCRIPTION
This is an abstract base class for L<TAP::Parser::Source> handlers / handlers.
A C<TAP::Parser::SourceHandler> does whatever is necessary to produce & capture
a stream of TAP from the I<raw> source, and package it up in a
L<TAP::Parser::Iterator> for the parser to consume.
C<SourceHandlers> must implement the I<source detection & handling> interface
used by L<TAP::Parser::IteratorFactory>. At 2 methods, the interface is pretty
simple: L</can_handle> and L</make_source>.
Unless you're writing a new L<TAP::Parser::SourceHandler>, a plugin, or
subclassing L<TAP::Parser>, you probably won't need to use this module directly.
=head1 METHODS
=head2 Class Methods
=head3 C<can_handle>
I<Abstract method>.
my $vote = $class->can_handle( $source );
C<$source> is a L<TAP::Parser::Source>.
Returns a number between C<0> & C<1> reflecting how confidently the raw source
can be handled. For example, C<0> means the source cannot handle it, C<0.5>
means it may be able to, and C<1> means it definitely can. See
L<TAP::Parser::IteratorFactory/detect_source> for details on how this is used.
=cut
sub can_handle {
my ( $class, $args ) = @_;
$class->_croak(
"Abstract method 'can_handle' not implemented for $class!");
return;
}
=head3 C<make_iterator>
I<Abstract method>.
my $iterator = $class->make_iterator( $source );
C<$source> is a L<TAP::Parser::Source>.
Returns a new L<TAP::Parser::Iterator> object for use by the L<TAP::Parser>.
C<croak>s on error.
=cut
sub make_iterator {
my ( $class, $args ) = @_;
$class->_croak(
"Abstract method 'make_iterator' not implemented for $class!");
return;
}
1;
__END__
=head1 SUBCLASSING
Please see L<TAP::Parser/SUBCLASSING> for a subclassing overview, and any
of the subclasses that ship with this module as an example. What follows is
a quick overview.
Start by familiarizing yourself with L<TAP::Parser::Source> and
L<TAP::Parser::IteratorFactory>. L<TAP::Parser::SourceHandler::RawTAP> is
the easiest sub-class to use an an example.
It's important to point out that if you want your subclass to be automatically
used by L<TAP::Parser> you'll have to and make sure it gets loaded somehow.
If you're using L<prove> you can write an L<App::Prove> plugin. If you're
using L<TAP::Parser> or L<TAP::Harness> directly (e.g. through a custom script,
L<ExtUtils::MakeMaker>, or L<Module::Build>) you can use the C<config> option
which will cause L<TAP::Parser::IteratorFactory/load_sources> to load your
subclass).
Don't forget to register your class with
L<TAP::Parser::IteratorFactory/register_handler>.
=head2 Example
package MySourceHandler;
use strict;
use vars '@ISA'; # compat with older perls
use MySourceHandler; # see TAP::Parser::SourceHandler
use TAP::Parser::IteratorFactory;
@ISA = qw( TAP::Parser::SourceHandler );
TAP::Parser::IteratorFactory->register_handler( __PACKAGE__ );
sub can_handle {
my ( $class, $src ) = @_;
my $meta = $src->meta;
my $config = $src->config_for( $class );
if ($config->{accept_all}) {
return 1.0;
} elsif (my $file = $meta->{file}) {
return 0.0 unless $file->{exists};
return 1.0 if $file->{lc_ext} eq '.tap';
return 0.9 if $file->{shebang} && $file->{shebang} =~ /^#!.+tap/;
return 0.5 if $file->{text};
return 0.1 if $file->{binary};
} elsif ($meta->{scalar}) {
return 0.8 if $$raw_source_ref =~ /\d\.\.\d/;
return 0.6 if $meta->{has_newlines};
} elsif ($meta->{array}) {
return 0.8 if $meta->{size} < 5;
return 0.6 if $raw_source_ref->[0] =~ /foo/;
return 0.5;
} elsif ($meta->{hash}) {
return 0.6 if $raw_source_ref->{foo};
return 0.2;
}
return 0;
}
sub make_iterator {
my ($class, $source) = @_;
# this is where you manipulate the source and
# capture the stream of TAP in an iterator
# either pick a TAP::Parser::Iterator::* or write your own...
my $iterator = TAP::Parser::Iterator::Array->new([ 'foo', 'bar' ]);
return $iterator;
}
1;
=head1 AUTHORS
TAPx Developers.
Source detection stuff added by Steve Purkis
=head1 SEE ALSO
L<TAP::Object>,
L<TAP::Parser>,
L<TAP::Parser::Source>,
L<TAP::Parser::Iterator>,
L<TAP::Parser::IteratorFactory>,
L<TAP::Parser::SourceHandler::Executable>,
L<TAP::Parser::SourceHandler::Perl>,
L<TAP::Parser::SourceHandler::File>,
L<TAP::Parser::SourceHandler::Handle>,
L<TAP::Parser::SourceHandler::RawTAP>
=cut
| Dokaponteam/ITF_Project | xampp/perl/lib/TAP/Parser/SourceHandler.pm | Perl | mit | 5,246 |
package Data::Section::Simple;
use strict;
use 5.008_001;
our $VERSION = '0.05';
use base qw(Exporter);
our @EXPORT_OK = qw(get_data_section);
sub new {
my($class, $pkg) = @_;
bless { package => $pkg || caller }, $class;
}
sub get_data_section {
my $self = ref $_[0] ? shift : __PACKAGE__->new(scalar caller);
if (@_) {
my $all = $self->get_data_section;
return unless $all;
return $all->{$_[0]};
} else {
my $d = do { no strict 'refs'; \*{$self->{package}."::DATA"} };
return unless defined fileno $d;
seek $d, 0, 0;
my $content = join '', <$d>;
$content =~ s/^.*\n__DATA__\n/\n/s; # for win32
$content =~ s/\n__END__\n.*$/\n/s;
my @data = split /^@@\s+(.+?)\s*\r?\n/m, $content;
shift @data; # trailing whitespaces
my $all = {};
while (@data) {
my ($name, $content) = splice @data, 0, 2;
$all->{$name} = $content;
}
return $all;
}
}
1;
__END__
=encoding utf-8
=for stopwords
=head1 NAME
Data::Section::Simple - Read data from __DATA__
=head1 SYNOPSIS
use Data::Section::Simple qw(get_data_section);
# Functional interface -- reads from caller package __DATA__
my $all = get_data_section; # All data in hash reference
my $foo = get_data_section('foo.html');
# OO - allows reading from other packages
my $reader = Data::Section::Simple->new($package);
my $all = $reader->get_data_section;
__DATA__
@@ foo.html
<html>
<body>Hello</body>
</html>
@@ bar.tt
[% IF true %]
Foo
[% END %]
=head1 DESCRIPTION
Data::Section::Simple is a simple module to extract data from
C<__DATA__> section of the file.
=head1 LIMITATIONS
As the name suggests, this module is a simpler version of the
excellent L<Data::Section>. If you want more functionalities such as
merging data sections or changing header patterns, use
L<Data::Section> instead.
This module does not implement caching (yet) which means in every
C<get_data_section> or C<< get_data_section($name) >> this module
seeks and re-reads the data section. If you want to avoid doing so for
the better performance, you should implement caching in your own
caller code.
=head1 BUGS
=head2 __DATA__ appearing elsewhere
If you data section has literal C<__DATA__> in the data section, this
module might be tricked by that. Although since its pattern match is
greedy, C<__DATA__> appearing I<before> the actual data section
(i.e. in the code) might be okay.
This is by design -- in theory you can C<tell> the DATA handle before
reading it, but then reloading the data section of the file (handy for
developing inline templates with PSGI web applications) would fail
because the pos would be changed.
If you don't like this design, again, use the superior
L<Data::Section>.
=head2 utf8 pragma
If you enable L<utf8> pragma in the caller's package (or the package
you're inspecting with the OO interface), the data retrieved via
C<get_data_section> is decoded, but otherwise undecoded. There's no
reliable way for this module to programmatically know whether utf8
pragma is enabled or not: it's your responsibility to handle them
correctly.
=head1 AUTHOR
Tatsuhiko Miyagawa E<lt>miyagawa@bulknews.netE<gt>
=head1 COPYRIGHT
Copyright 2010- Tatsuhiko Miyagawa
The code to read DATA section is based on Mojo::Command get_all_data:
Copyright 2008-2010 Sebastian Riedel
=head1 LICENSE
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=head1 SEE ALSO
L<Data::Section> L<Inline::Files>
=cut
| edvakf/isu3pre | perl/local/lib/perl5/Data/Section/Simple.pm | Perl | mit | 3,622 |
#!/usr/bin/perl -w
;#
;# ntp.pl,v 3.1 1993/07/06 01:09:09 jbj Exp
;#
;# process loop filter statistics file and either
;# - show statistics periodically using gnuplot
;# - or print a single plot
;#
;# Copyright (c) 1992
;# Rainer Pruy Friedrich-Alexander Universitaet Erlangen-Nuernberg
;#
;#
;#############################################################
package ntp;
$NTP_version = 2;
$ctrl_mode=6;
$byte1 = (($NTP_version & 0x7)<< 3) & 0x34 | ($ctrl_mode & 0x7);
$MAX_DATA = 468;
$sequence = 0; # initial sequence number incred before used
$pad=4;
$do_auth=0; # no possibility today
$keyid=0;
;#list if known keys (passwords)
%KEYS = ( 0, "\200\200\200\200\200\200\200\200",
);
;#-----------------------------------------------------------------------------
;# access routines for ntp control packet
;# NTP control message format
;# C LI|VN|MODE LI 2bit=00 VN 3bit=2(3) MODE 3bit=6 : $byte1
;# C R|E|M|Op R response E error M more Op opcode
;# n sequence
;# n status
;# n associd
;# n offset
;# n count
;# a+ data (+ padding)
;# optional authentication data
;# N key
;# N2 checksum
;# first byte of packet
sub pkt_LI { return ($_[$[] >> 6) & 0x3; }
sub pkt_VN { return ($_[$[] >> 3) & 0x7; }
sub pkt_MODE { return ($_[$[] ) & 0x7; }
;# second byte of packet
sub pkt_R { return ($_[$[] & 0x80) == 0x80; }
sub pkt_E { return ($_[$[] & 0x40) == 0x40; }
sub pkt_M { return ($_[$[] & 0x20) == 0x20; }
sub pkt_OP { return $_[$[] & 0x1f; }
;#-----------------------------------------------------------------------------
sub setkey
{
local($id,$key) = @_;
$KEYS{$id} = $key if (defined($key));
if (! defined($KEYS{$id}))
{
warn "Key $id not yet specified - key not changed\n";
return undef;
}
return ($keyid,$keyid = $id)[$[];
}
;#-----------------------------------------------------------------------------
sub numerical { $a <=> $b; }
;#-----------------------------------------------------------------------------
sub send #'
{
local($fh,$opcode, $associd, $data,$address) = @_;
$fh = caller(0)."'$fh";
local($junksize,$junk,$packet,$offset,$ret);
$offset = 0;
$sequence++;
while(1)
{
$junksize = length($data);
$junksize = $MAX_DATA if $junksize > $MAX_DATA;
($junk,$data) = $data =~ /^(.{$junksize})(.*)$/;
$packet
= pack("C2n5a".(($junk eq "") ? 0 : &pad($junksize+12,$pad)-12),
$byte1,
($opcode & 0x1f) | ($data ? 0x20 : 0),
$sequence,
0, $associd,
$offset, $junksize, $junk);
if ($do_auth)
{
;# not yet
}
$offset += $junksize;
if (defined($address))
{
$ret = send($fh, $packet, 0, $address);
}
else
{
$ret = send($fh, $packet, 0);
}
if (! defined($ret))
{
warn "send failed: $!\n";
return undef;
}
elsif ($ret != length($packet))
{
warn "send failed: sent only $ret from ".length($packet). "bytes\n";
return undef;
}
return $sequence unless $data;
}
}
;#-----------------------------------------------------------------------------
;# status interpretation
;#
sub getval
{
local($val,*list) = @_;
return $list{$val} if defined($list{$val});
return sprintf("%s#%d",$list{"-"},$val) if defined($list{"-"});
return "unknown-$val";
}
;#---------------------------------
;# system status
;#
;# format: |LI|CS|SECnt|SECode| LI=2bit CS=6bit SECnt=4bit SECode=4bit
sub ssw_LI { return ($_[$[] >> 14) & 0x3; }
sub ssw_CS { return ($_[$[] >> 8) & 0x3f; }
sub ssw_SECnt { return ($_[$[] >> 4) & 0xf; }
sub ssw_SECode { return $_[$[] & 0xf; }
%LI = ( 0, "leap_none", 1, "leap_add_sec", 2, "leap_del_sec", 3, "sync_alarm", "-", "leap");
%ClockSource = (0, "sync_unspec",
1, "sync_pps",
2, "sync_lf_clock",
3, "sync_hf_clock",
4, "sync_uhf_clock",
5, "sync_local_proto",
6, "sync_ntp",
7, "sync_udp/time",
8, "sync_wristwatch",
9, "sync_telephone",
"-", "ClockSource",
);
%SystemEvent = (0, "event_unspec",
1, "event_freq_not_set",
2, "event_freq_set",
3, "event_spike_detect",
4, "event_freq_mode",
5, "event_clock_sync",
6, "event_restart",
7, "event_panic_stop",
8, "event_no_sys_peer",
9, "event_leap_armed",
10, "event_leap_disarmed",
11, "event_leap_event",
12, "event_clock_step",
13, "event_kern",
14, "event_loaded_leaps",
15, "event_stale_leaps",
"-", "event",
);
sub LI
{
&getval(&ssw_LI($_[$[]),*LI);
}
sub ClockSource
{
&getval(&ssw_CS($_[$[]),*ClockSource);
}
sub SystemEvent
{
&getval(&ssw_SECode($_[$[]),*SystemEvent);
}
sub system_status
{
return sprintf("%s, %s, %d event%s, %s", &LI($_[$[]), &ClockSource($_[$[]),
&ssw_SECnt($_[$[]), ((&ssw_SECnt($_[$[])==1) ? "" : "s"),
&SystemEvent($_[$[]));
}
;#---------------------------------
;# peer status
;#
;# format: |PStat|PSel|PCnt|PCode| Pstat=6bit PSel=2bit PCnt=4bit PCode=4bit
sub psw_PStat_config { return ($_[$[] & 0x8000) == 0x8000; }
sub psw_PStat_authenable { return ($_[$[] & 0x4000) == 0x4000; }
sub psw_PStat_authentic { return ($_[$[] & 0x2000) == 0x2000; }
sub psw_PStat_reach { return ($_[$[] & 0x1000) == 0x1000; }
sub psw_PStat_bcast { return ($_[$[] & 0x0800) == 0x0800; }
sub psw_PStat { return ($_[$[] >> 10) & 0x3f; }
sub psw_PSel { return ($_[$[] >> 8) & 0x3; }
sub psw_PCnt { return ($_[$[] >> 4) & 0xf; }
sub psw_PCode { return $_[$[] & 0xf; }
%PeerSelection = (0, "sel_reject",
1, "sel_falsetick",
2, "sel_excess",
3, "sel_outlier",
4, "sel_candidate",
5, "sel_backup",
6, "sel_sys.peer",
6, "sel_pps.peer",
"-", "PeerSel",
);
%PeerEvent = (0, "event_unspec",
1, "event_mobilize",
2, "event_demobilize",
3, "event_unreach",
4, "event_reach",
5, "event_restart",
6, "event_no_reply",
7, "event_rate_exceed",
8, "event_denied",
9, "event_leap_armed",
10, "event_sys_peer",
11, "event_clock_event",
12, "event_bad_auth",
13, "event_popcorn",
14, "event_intlv_mode",
15, "event_intlv_err",
"-", "event",
);
sub PeerSelection
{
&getval(&psw_PSel($_[$[]),*PeerSelection);
}
sub PeerEvent
{
&getval(&psw_PCode($_[$[]),*PeerEvent);
}
sub peer_status
{
local($x) = ("");
$x .= "config," if &psw_PStat_config($_[$[]);
$x .= "authenable," if &psw_PStat_authenable($_[$[]);
$x .= "authentic," if &psw_PStat_authentic($_[$[]);
$x .= "reach," if &psw_PStat_reach($_[$[]);
$x .= "bcast," if &psw_PStat_bcast($_[$[]);
$x .= sprintf(" %s, %d event%s, %s", &PeerSelection($_[$[]),
&psw_PCnt($_[$[]), ((&psw_PCnt($_[$[]) == 1) ? "" : "s"),
&PeerEvent($_[$[]));
return $x;
}
;#---------------------------------
;# clock status
;#
;# format: |CStat|CEvnt| CStat=8bit CEvnt=8bit
sub csw_CStat { return ($_[$[] >> 8) & 0xff; }
sub csw_CEvnt { return $_[$[] & 0xff; }
%ClockStatus = (0, "clk_nominal",
1, "clk_timeout",
2, "clk_badreply",
3, "clk_fault",
4, "clk_badsig",
5, "clk_baddate",
6, "clk_badtime",
"-", "clk",
);
sub clock_status
{
return sprintf("%s, last %s",
&getval(&csw_CStat($_[$[]),*ClockStatus),
&getval(&csw_CEvnt($_[$[]),*ClockStatus));
}
;#---------------------------------
;# error status
;#
;# format: |Err|reserved| Err=8bit
;#
sub esw_Err { return ($_[$[] >> 8) & 0xff; }
%ErrorStatus = (0, "err_unspec",
1, "err_auth_fail",
2, "err_invalid_fmt",
3, "err_invalid_opcode",
4, "err_unknown_assoc",
5, "err_unknown_var",
6, "err_invalid_value",
7, "err_adm_prohibit",
);
sub error_status
{
return sprintf("%s", &getval(&esw_Err($_[$[]),*ErrorStatus));
}
;#-----------------------------------------------------------------------------
;#
;# cntrl op name translation
%CntrlOpName = (0, "reserved",
1, "read_status",
2, "read_variables",
3, "write_variables",
4, "read_clock_variables",
5, "write_clock_variables",
6, "set_trap",
7, "trap_response",
8, "configure",
9, "saveconf",
10, "read_mru",
11, "read_ordlist",
12, "rqst_nonce",
31, "unset_trap", # !!! unofficial !!!
"-", "cntrlop",
);
sub cntrlop_name
{
return &getval($_[$[],*CntrlOpName);
}
;#-----------------------------------------------------------------------------
$STAT_short_pkt = 0;
$STAT_pkt = 0;
;# process a NTP control message (response) packet
;# returns a list ($ret,$data,$status,$associd,$op,$seq,$auth_keyid)
;# $ret: undef --> not yet complete
;# "" --> complete packet received
;# "ERROR" --> error during receive, bad packet, ...
;# else --> error packet - list may contain useful info
sub handle_packet
{
local($pkt,$from) = @_; # parameters
local($len_pkt) = (length($pkt));
;# local(*FRAGS,*lastseen);
local($li_vn_mode,$r_e_m_op,$seq,$status,$associd,$offset,$count,$data);
local($autch_keyid,$auth_cksum);
$STAT_pkt++;
if ($len_pkt < 12)
{
$STAT_short_pkt++;
return ("ERROR","short packet received");
}
;# now break packet apart
($li_vn_mode,$r_e_m_op,$seq,$status,$associd,$offset,$count,$data) =
unpack("C2n5a".($len_pkt-12),$pkt);
$data=substr($data,$[,$count);
if ((($len_pkt - 12) - &pad($count,4)) >= 12)
{
;# looks like an authenticator
($auth_keyid,$auth_cksum) =
unpack("Na8",substr($pkt,$len_pkt-12+$[,12));
$STAT_auth++;
;# no checking of auth_cksum (yet ?)
}
if (&pkt_VN($li_vn_mode) != $NTP_version)
{
$STAT_bad_version++;
return ("ERROR","version ".&pkt_VN($li_vn_mode)."packet ignored");
}
if (&pkt_MODE($li_vn_mode) != $ctrl_mode)
{
$STAT_bad_mode++;
return ("ERROR", "mode ".&pkt_MODE($li_vn_mode)." packet ignored");
}
;# handle single fragment fast
if ($offset == 0 && &pkt_M($r_e_m_op) == 0)
{
$STAT_single_frag++;
if (&pkt_E($r_e_m_op))
{
$STAT_err_pkt++;
return (&error_status($status),
$data,$status,$associd,&pkt_OP($r_e_m_op),$seq,
$auth_keyid);
}
else
{
return ("",
$data,$status,$associd,&pkt_OP($r_e_m_op),$seq,
$auth_keyid);
}
}
else
{
;# fragment - set up local name space
$id = "$from$seq".&pkt_OP($r_e_m_op);
$ID{$id} = 1;
*FRAGS = "$id FRAGS";
*lastseen = "$id lastseen";
$STAT_frag++;
$lastseen = 1 if !&pkt_M($r_e_m_op);
if (!%FRAGS)
{
print((&pkt_M($r_e_m_op) ? " more" : "")."\n");
$FRAGS{$offset} = $data;
;# save other info
@FRAGS = ($status,$associd,&pkt_OP($r_e_m_op),$seq,$auth_keyid,$r_e_m_op);
}
else
{
print((&pkt_M($r_e_m_op) ? " more" : "")."\n");
;# add frag to previous - combine on the fly
if (defined($FRAGS{$offset}))
{
$STAT_dup_frag++;
return ("ERROR","duplicate fragment at $offset seq=$seq");
}
$FRAGS{$offset} = $data;
undef($loff);
foreach $off (sort numerical keys(%FRAGS))
{
next unless defined($FRAGS{$off});
if (defined($loff) &&
($loff + length($FRAGS{$loff})) == $off)
{
$FRAGS{$loff} .= $FRAGS{$off};
delete $FRAGS{$off};
last;
}
$loff = $off;
}
;# return packet if all frags arrived
;# at most two frags with possible padding ???
if ($lastseen && defined($FRAGS{0}) &&
(((scalar(@x=sort numerical keys(%FRAGS)) == 2) &&
(length($FRAGS{0}) + 8) > $x[$[+1]) ||
(scalar(@x=sort numerical keys(%FRAGS)) < 2)))
{
@x=((&pkt_E($r_e_m_op) ? &error_status($status) : ""),
$FRAGS{0},@FRAGS);
&pkt_E($r_e_m_op) ? $STAT_err_frag++ : $STAT_frag_all++;
undef(%FRAGS);
undef(@FRAGS);
undef($lastseen);
delete $ID{$id};
&main'clear_timeout($id);
return @x;
}
else
{
&main'set_timeout($id,time+$timeout,"&ntp'handle_packet_timeout(\"".unpack("H*",$id)."\");"); #'";
}
}
return (undef);
}
}
sub handle_packet_timeout
{
local($id) = @_;
local($r_e_m_op,*FRAGS,*lastseen,@x) = (@FRAGS[$[+5]);
*FRAGS = "$id FRAGS";
*lastseen = "$id lastseen";
@x=((&pkt_E($r_e_m_op) ? &error_status($status) : "TIMEOUT"),
$FRAGS{0},@FRAGS[$[ .. $[+4]);
$STAT_frag_timeout++;
undef(%FRAGS);
undef(@FRAGS);
undef($lastseen);
delete $ID{$id};
return @x;
}
sub pad
{
return $_[$[+1] * int(($_[$[] + $_[$[+1] - 1) / $_[$[+1]);
}
1;
| execunix/vinos | external/bsd/ntp/dist/scripts/monitoring/ntp.pl | Perl | apache-2.0 | 12,375 |
=pod
=head1 NAME
Locale::Codes::LangVar - standard codes for language variation identification
=head1 SYNOPSIS
use Locale::Codes::LangVar;
$lvar = code2langvar('acm'); # $lvar gets 'Mesopotamian Arabic'
$code = langvar2code('Mesopotamian Arabic'); # $code gets 'acm'
@codes = all_langvar_codes();
@names = all_langvar_names();
=head1 DESCRIPTION
The C<Locale::Codes::LangVar> module provides access to standard codes
used for identifying language variations, such as those as defined in
the IANA language registry.
Most of the routines take an optional additional argument which
specifies the code set to use. If not specified, the default IANA
language registry codes will be used.
=head1 SUPPORTED CODE SETS
There are several different code sets you can use for identifying
language variations. A code set may be specified using either a name, or a
constant that is automatically exported by this module.
For example, the two are equivalent:
$lvar = code2langvar('en','alpha-2');
$lvar = code2langvar('en',LOCALE_CODE_ALPHA_2);
The codesets currently supported are:
=over 4
=item B<alpha>
This is the set of alphanumeric codes from the IANA
language registry, such as 'arevela' for Eastern Armenian.
This code set is identified with the symbol C<LOCALE_LANGVAR_ALPHA>.
This is the default code set.
=back
=head1 ROUTINES
=over 4
=item B<code2langvar ( CODE [,CODESET] )>
=item B<langvar2code ( NAME [,CODESET] )>
=item B<langvar_code2code ( CODE ,CODESET ,CODESET2 )>
=item B<all_langvar_codes ( [CODESET] )>
=item B<all_langvar_names ( [CODESET] )>
=item B<Locale::Codes::LangVar::rename_langvar ( CODE ,NEW_NAME [,CODESET] )>
=item B<Locale::Codes::LangVar::add_langvar ( CODE ,NAME [,CODESET] )>
=item B<Locale::Codes::LangVar::delete_langvar ( CODE [,CODESET] )>
=item B<Locale::Codes::LangVar::add_langvar_alias ( NAME ,NEW_NAME )>
=item B<Locale::Codes::LangVar::delete_langvar_alias ( NAME )>
=item B<Locale::Codes::LangVar::rename_langvar_code ( CODE ,NEW_CODE [,CODESET] )>
=item B<Locale::Codes::LangVar::add_langvar_code_alias ( CODE ,NEW_CODE [,CODESET] )>
=item B<Locale::Codes::LangVar::delete_langvar_code_alias ( CODE [,CODESET] )>
These routines are all documented in the Locale::Codes::API man page.
=back
=head1 SEE ALSO
=over 4
=item B<Locale::Codes>
The Locale-Codes distribution.
=item B<Locale::Codes::API>
The list of functions supported by this module.
=item B<http://www.iana.org/assignments/language-subtag-registry>
The IANA language subtag registry.
=back
=head1 AUTHOR
See Locale::Codes for full author history.
Currently maintained by Sullivan Beck (sbeck@cpan.org).
=head1 COPYRIGHT
Copyright (c) 2011-2012 Sullivan Beck
This module is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.
=cut
| leighpauls/k2cro4 | third_party/perl/perl/lib/Locale/Codes/LangVar.pod | Perl | bsd-3-clause | 2,874 |
#!/usr/bin/perl -w
# Copyright 2010 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may not
# use this file except in compliance with the License. A copy of the License is
# located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.
use strict;
# begin customizing here
my $CURL = "curl";
# stop customizing here
# you might need to use CPAN to get these modules.
# run perl -MCPAN -e "install <module>" to get them.
use Digest::HMAC_SHA1;
use FindBin;
use MIME::Base64 qw(encode_base64);
use Getopt::Long qw(GetOptions);
use File::Temp qw(tempfile);
use File::Basename qw(basename);
use Fcntl qw/F_SETFD F_GETFD/;
use IO::Handle;
use constant STAT_MODE => 2;
use constant STAT_UID => 4;
my $PROGNAME = basename($0);
my %awsSecretAccessKeys = (); # this gets filled in by evaling the user's secrets file
my $SECRETSFILENAME=".aws-secrets";
my $EXECFILE=$FindBin::Bin;
my $LOCALSECRETSFILE = $EXECFILE . "/" . $SECRETSFILENAME;
my $HOMESECRETSFILE = $ENV{HOME} . "/" . $SECRETSFILENAME;
my $DEFAULTSECRETSFILE = -f $LOCALSECRETSFILE? $LOCALSECRETSFILE : $HOMESECRETSFILE;
my $secretsFile = $DEFAULTSECRETSFILE;
my $keyFile;
my $keyFriendlyName;
my $debug = 0;
GetOptions(
'keyfile:s' => \$keyFile,
'keyname=s' => \$keyFriendlyName,
'debug' => \$debug,
);
$secretsFile = $keyFile if defined $keyFile;
if (!defined $keyFriendlyName) {
print STDERR "Usage: $PROGNAME --keyname <friendly key name> -- [curl-options]\n\n";
print_example_usage();
exit 1;
}
if (-f $secretsFile) {
open(my $CONFIG, $secretsFile) || die "can't open $secretsFile: $!";
my @stats = stat($CONFIG);
if (($stats[STAT_UID] != $<) || $stats[STAT_MODE] & 066) {
die "I refuse to read your credentials from $secretsFile as this file is " .
"readable by, writable by or owned by someone else. Try " .
"chmod 600 $secretsFile";
}
my @lines = <$CONFIG>;
close $CONFIG;
eval("@lines");
die "Failed to eval() file $secretsFile:\n$@\n" if ($@);
} else {
print_secrets_file_usage();
exit 2;
}
# look up the key by friendly name
my $keyentry = $awsSecretAccessKeys{$keyFriendlyName};
if (!defined $keyentry) {
print STDERR "I can't find a key with friendly name $keyFriendlyName.\n";
print STDERR "Do you need to add it to $secretsFile?\n";
print STDERR "\n";
if (scalar(%awsSecretAccessKeys)) {
print STDERR "Or maybe try one of these keys that I already know about:\n";
print STDERR "\t" . join(", ", keys(%awsSecretAccessKeys)) . "\n";
}
exit 3;
}
my $aws_key_id = $keyentry->{id};
my $aws_secret_key = $keyentry->{key};
# don't assume the local clock is correct -- fetch the Date according to the server
my $base_url = find_base_url_from_args(@ARGV);
if (!defined $base_url) {
print STDERR "I couldn't find anything that looks like a URL in your curl arguments.\n\n";
print_example_usage();
exit 4;
}
my $server_date = fetch_server_date($base_url);
# construct the request signature
my $string_to_sign = "$server_date";
my $hmac = Digest::HMAC_SHA1->new($aws_secret_key);
$hmac->add($string_to_sign);
my $signature = encode_base64($hmac->digest, "");
# Pass our (secret) arguments to curl using a temporary file, to avoid exposing them on the command line.
# Can't use STDIN for this purpose because that would prevent the caller from using that stream
# This is secure because tempfile() guarantees the new file is chmod 600
my ($curl_args_file, $curl_args_file_name) = tempfile(UNLINK => 1);
print $curl_args_file "header = \"Date: $server_date\"\n";
print $curl_args_file "header = \"X-Amzn-Authorization: AWS3-HTTPS AWSAccessKeyId=$aws_key_id,Algorithm=HmacSHA1,Signature=$signature\"\n";
close $curl_args_file or die "Couldn't close curl config file: $!";
# fork/exec curl, forwarding the user's command line arguments
system($CURL, @ARGV, "--config", $curl_args_file_name);
my $curl_result = $?;
if ($curl_result == -1) {
die "failed to execute $CURL: $!";
} elsif ($curl_result & 127) {
printf "$CURL died with signal %d, %s coredump\n",
($curl_result & 127), ($curl_result & 128) ? "with" : "without";
exit 4;
}
# forward curl's exit code
exit $? >> 8;
sub print_secrets_file_usage {
print STDERR <<END_WARNING;
Welcome to AWS DNS curl! You'll need to install your AWS credentials to get started.
For security reasons, this tool will not accept your AWS secret access key on the
command line. Instead, you need to store them in a file named $secretsFile.
This file must be owned by you, and must be readable by only you.
For example:
\$ cat $secretsFile
\%awsSecretAccessKeys = (
# my personal account
'fred-personal' => {
id => '1ME55KNV6SBTR7EXG0R2',
key => 'zyMrlZUKeG9UcYpwzlPko/+Ciu0K2co0duRM3fhi',
},
# my corporate account
'fred-work' => {
id => '1ATXQ3HHA59CYF1CVS02',
key => 'WQY4SrSS95pJUT95V6zWea01gBKBCL6PI0cdxeH8',
},
);
\$ chmod 600 $secretsFile
END_WARNING
return;
}
sub print_example_usage {
my ($prog) = @_;
print STDERR "Examples:\n";
print STDERR "\t\$ $PROGNAME --keyname fred-personal -- -X POST -H \"Content-Type: text/xml; charset=UTF-8\" --upload-file create_request.xml https://route53.amazonaws.com/2010-10-01/hostedzone\t# create new hosted zone\n";
print STDERR "\t\$ $PROGNAME --keyname fred-personal -- https://route53.amazonaws.com/2010-10-01/hostedzone/Z123456\t# get hosted zone";
print STDERR "\t\$ $PROGNAME --keyname fred-personal -- https://route53.amazonaws.com/2010-10-01/hostedzone\t# list hosted zones";
return;
}
# search command line arguments for the first thing that looks like an URL, and return just the http://server:port part of it
sub find_base_url_from_args {
my (@args) = @_;
for my $arg (@args) {
return $1 if ($arg =~ m|^(https?://[^:]+(:\d+)?)\S+|);
}
return;
}
sub fetch_server_date {
my ($url) = @_;
my $curl_output_lines = run_cmd_read($CURL, "--progress-bar", "-I", "--max-time", "5", "--url", $url, "--insecure");
for my $line (@$curl_output_lines) {
if ($line =~ /^Date:\s+([[:print:]]+)/) {
return $1;
}
}
die "Could not find a Date header in server HEAD response: " . join(";", @$curl_output_lines);
}
sub run_cmd_read {
my ($cmd, @args) = @_;
my $cmd_str = $cmd . " " . join(" ", @args);
my $pid = open(my $README, "-|");
die "cannot fork: $!" unless defined $pid;
if ($pid == 0) {
exec($cmd, @args) or die "Can't exec $cmd : $!";
}
# slurp the output
my @output = (<$README>);
my $result = close($README);
unless ($result) {
die "Error closing $cmd pipe: $!" if $!;
}
my $exit_code = ($? >> 8);
die "Ouch, $cmd_str failed with exit status $exit_code\n" if ($exit_code != 0);
return \@output;
}
| ravibhure/cookbooks_public_120112 | cookbooks/sys_dns/files/default/dnscurl.pl | Perl | mit | 7,453 |
use strict;
use vars qw($VERSION %IRSSI);
use Irssi qw(signal_add signal_stop signal_continue);
$VERSION = '1.00';
%IRSSI = (
authors => 'Teddy Wing',
contact => 'irssi@teddywing.com',
name => 'HipChat STFU',
description => 'Silences annoying messages originating from HipChat.',
license => 'MIT',
);
sub prettify_hipchat {
my ($input) = @_;
# Grab browse link
my ($link) = $input =~ /"([^"]+\/browse\/[^"]+)"/;
# Remove HTML tags
$input =~ s/<.+?>//g;
# Trim whitespace
$input =~ s/^(\s| )+|(\s| )+$//g;
# Trim whitespace between words
$input =~ s/(\s| ){2,}/ /g;
# Remove Priority
$input =~ s/Priority://g;
# Remove Status
$input =~ s/Status://g;
# Construct start message
if ($link) {
$input =~ s/Created by (.+)$/($1) ($link)/g;
}
return $input;
};
sub hipchat_stfu {
my ($server, $text, $nick, $address, $target) = @_;
if ($server->{'chatnet'} eq 'Bitlbee' &&
$nick eq 'root') {
my $msg = prettify_hipchat($text);
if ($msg eq '') {
signal_stop();
}
else {
signal_continue($server, $msg, $nick, $address, $target);
}
}
};
signal_add('message public', \&hipchat_stfu);
| teddywing/irssi-hipchat-stfu | hipchat-stfu.pl | Perl | mit | 1,165 |
package CGI::OptimalQuery::InteractiveFilter;
use strict;
use warnings;
no warnings qw( uninitialized );
use base 'CGI::OptimalQuery::Base';
use Data::Dumper;
use DBIx::OptimalQuery();
use CGI();
my $DEFAULT_CSS = <<'TILEND';
<STYLE type="text/css">
/* ----- base functionality ----- */
form.filterForm td.lp_col,
form.filterForm td.rp_col {
text-align: center;
}
form.filterForm td.lp_col input,
form.filterForm td.rp_col input {
color: #999999;
background-color: white;
border: 1px solid #efefef;
font-size: 1em;
width: 2em;
}
form.filterForm td.l_col input.colvalbtn { display: none; }
form.filterForm td.d_col input { color: #990000; background-color: white; border: 1px solid white;}
form.filterForm tr.footer td.d_col input { background-color: #990000; color: white; border: 1px solid #666666;}
form.filterForm .d_col { color: #990000; }
div.RO_NAMED_FILTER {
background-color: #efefef;
color: #222222;
font-size: 1.1em;
text-align: center;
border: 1px solid #666666;
}
form.filterForm input,
form.filterForm select {
border: 1px solid #666666;
background-color: #efefef;
padding: 2px;
vertical-align: middle;
}
td.f_col { text-align: center; }
form.filterForm .hide { display: none; }
/* -------------------- prefs -------------------- */
form.filterForm .submit_off,.add_off { display: none; }
form.filterForm .c_col { text-align: center; }
form.filterForm input.submit_ok { background-color: lightgreen; }
form.filterForm input.submit_off { background-color: yellow; }
form.filterForm .paren_warn { text-align: center; background-color: yellow; }
form.filterForm .paren_match { display: none; }
form.filterForm .delbtn { color: white; background-color: #990000; }
form.filterForm .noparen { color: white; }
</STYLE>
TILEND
=comment CSS MORE POSSIBILITIES
# Simplest mode
form.filterForm .colvalbtn { display:none; }
form.filterForm .noparen { display:none; }
form.filterForm #paren_warn { display:none; }
# Disable deleting controls
form.filterForm .d_col { display:none; }
# other possibilities ...
form.filterForm label:after { content: " mark"; }
<!-- Different Style Sheet possibilites (see documentation) -->
<link title="full" rel="stylesheet" type="text/css" href="http:///css/OQfilter_full.css" />
<link title="simplest" rel="alternate stylesheet" type="text/css" href="http:///css/OQfilter_simplest.css" />
<link title="test" rel="alternate stylesheet" type="text/css" href="http:///css/OQfilter_test.css" />
=cut
# ------------------------- new -------------------------
sub new {
my $pack = shift;
my $o = $pack->SUPER::new(@_);
$$o{view} = '';
$$o{schema}{options}{'CGI::OptimalQuery::InteractiveFilter'}{css} ||= $DEFAULT_CSS;
$o->process_actions();
return $o;
}
# ------------------------- print -------------------------
sub output {
my $o = shift;
$$o{output_handler}->(CGI::header());
my $view = $$o{view};
$$o{output_handler}->($o->$view()) if $o->can($view);
return undef;
}
=comment
Grammar Translations: basically this describes how to convert rules
into elements of an expression array. Each element in this array
is a hash ref with keys: L_PAREN, R_PAREN, ANDOR, CMPOP, R_VALUE,
L_COLMN, R_COLMN, FUNCT, ARG_XYZ. Later this array can be translated
to CGI params that represent the filter for an HTML form.
Notice: The hash key is the rule name, the value is a sub ref where
the following args are defined:
$_[0] is $oq
$_[1] is rule name
$_[2] is token 1, $_[3] is token 2, etc ...
=cut
my %translations = (
# *** RULE ***
# exp:
# '(' exp ')' logicOp exp
# | '(' exp ')'
# | comparisonExp logicOp exp
# | comparisonExp
'exp' => sub {
# expression array is just an array of exp
# each element is a hashref containing keys
# L_PAREN, R_PAREN, ANDOR, CMPOP, R_VALUE,
# L_COLMN, R_COLMN, FUNCT, ARG_XYZ
my $expression_array;
# handle tokens:
# '(' exp ')' logicOp exp
# | '(' exp ')'
if ($_[2] eq '(') {
$expression_array = $_[3];
$$expression_array[0]{L_PAREN}++;
$$expression_array[-1]{R_PAREN}++;
# handle tokens: logicOp exp
if (exists $_[5]{ANDOR} && ref($_[6]) eq 'ARRAY') {
$$expression_array[-1]{ANDOR} = $_[5]{ANDOR};
push @$expression_array, @{ $_[6] }; # append exp
}
}
# handle tokens:
# comparisonExp logicOp exp
# | comparisonExp
else {
$expression_array = [ $_[2] ];
# add: logicOp exp
if (exists $_[3]{ANDOR} && ref($_[4]) eq 'ARRAY') {
$$expression_array[-1]{ANDOR} = $_[3]{ANDOR};
push @$expression_array, @{ $_[4] }; # append exp
}
}
return $expression_array;
},
# *** RULE ***
# namedFilter
# | colAlias compOp colAlias
# | colAlias compOp bindVal
'comparisonExp' => sub {
# if not a named filter
# combine CMPOP and R_VALUE | R_COLMN in
if (exists $_[2]{COLMN}) {
$_[2]{L_COLMN} = delete $_[2]{COLMN};
$_[2]{CMPOP} = $_[3]{CMPOP};
if (! ref $_[4]) { $_[2]{R_VALUE} = $_[4]; }
else { $_[2]{R_COLMN} = $_[4]{COLMN}; }
}
return $_[2];
},
# remove quotes from string
'quotedString' => sub { $_ = $_[2]; s/^\'// || s/^\"//; s/\'$// || s/\"$//; $_; },
# *** RULE ***
# colAlias: '[' /\w+/ ']'
'colAlias' => sub {
die "could not find colAlias '$_[3]'" unless exists $_[0]{select}{$_[3]};
return { 'COLMN' => $_[3] };
},
# *** RULE *** logicOp: /and/i | /or/i
'logicOp' => sub { { ANDOR => uc($_[2]) } },
# *** RULE *** compOp: '=' | '!=' | '<' |, ....
'compOp' => sub { { CMPOP => lc($_[2]) } },
# *** RULE *** nullComp: /is\ null/i | /is\ not\ null/i
'namedFilter' => sub {
die "could not find named filter '$_[2]'" unless exists $_[0]{named_filters}{$_[2]};
my $rv = { 'FUNCT' => $_[2].'()' };
my %args = @{ $_[4] } if ref($_[4]) eq 'ARRAY';
foreach my $key (keys %args) { $$rv{'ARG_'.$key} = $args{$key}; }
return $rv;
},
# just return the first token for all other rules not specified
'*default*' => sub { $_[2] }
);
# ------------------------- process actions -------------------------
sub process_actions {
my $o = shift;
my $q = $$o{q};
$$o{view} = 'html_filter_form';
# should we load a fresh filter into the appropriate params
# representing the filter?
if ($q->param('filter') ne '') {
my $expression_array = $$o{oq}->parse($DBIx::OptimalQuery::filterGrammar,
$q->param('filter'), \%translations);
die "bad filter!\nfilter= ".$q->param('filter').
"\nexp=".Dumper( $expression_array )."\n" unless ref($expression_array) eq 'ARRAY';
# fill in the params representing the filter state
my $i = 0;
foreach my $exp (@$expression_array) {
$i++;
while (my ($k,$v) = each %$exp) { $q->param('F'.$i.'_'.$k,$v); }
}
$q->param('FINDX', $i);
$q->param('hideParen', ($i < 3));
$$o{view} = 'html_filter_form';
}
# did the user request a new expression?
if ( defined $q->param('NEXT_EXPR')
&& scalar $q->param('NEXT_EXPR') ne '-- add new filter element --') {
my $val = scalar $q->param('NEXT_EXPR');
my $findx = $q->param('FINDX');
$findx = 0 unless $findx > 0;
$findx++;
my $pn = 'F' . $findx . '_';
if( $val =~ /\(\)\Z/ ) { # ends with a ()
$q->param($pn.'FUNCT', $val);
} else {
$q->param($pn.'L_COLMN', $val);
$q->param($pn.'L_VALUE', '');
if ($o->typ4clm($val) eq 'char' ||
$o->typ4clm($val) eq 'clob') {
$q->param($pn.'CMPOP', 'contains');
} else {
$q->param($pn.'CMPOP', '=');
}
}
$q->param('FINDX', $findx);
$q->param('hideParen', ( $findx < 3 ) );
$q->param('NEXT_EXPR', '--- Choose Next Filter ---');
$$o{view} = 'html_filter_form';
}
# did user submit the filter?
elsif ($q->param('act') eq 'submit_filter') {
my $ftxt = $o->recreateFilterString();
$q->param('filter', $ftxt);
$$o{view} = 'html_parent_update';
if ($$o{error}) {
$$o{view} = 'html_filter_form';
}
}
# did user request to delete filter
elsif ($q->param('act') eq 'submit_del') {
delselForm( $q );
$$o{view} = 'html_filter_form';
}
return undef;
}
# ------------------------- cmp_val -------------------------
sub cmp_val ( $$$$ ) {
my( $q, $pnam, $vals, $lbls ) = @_;
my $isUserVal = ( $q->param($pnam.'COLMN') eq ''
|| $q->param($pnam.'ISVAL') );
return
$q->button( -name=>$pnam.'BTN',
-label=>$isUserVal?'value:':'column:',
-onClick=>"toggle_value('$pnam');",
-class=>'colvalbtn')
. $q->hidden( -name=>$pnam.'ISVAL', -default=>$isUserVal )
. $q->textfield( -name=>$pnam.'VALUE',
-class=> ( $isUserVal ? 'val' : 'hide' ) )
. $q->popup_menu( -name=>$pnam.'COLMN',
-values=> $vals, -labels=> $lbls,
-onChange=>"submit_act('refresh');",
-class=> $isUserVal ? 'hide' : 'col');
}
# ------------------------- recreateFilterString -------------------------
sub recreateFilterString {
my $o = shift;
my $q = $$o{q};
# pull out the fuctions arguments from the form
my %funct_args = ();
foreach my $fak ( $q->param() ){
my @ary = split 'ARG_', $fak;
$funct_args{$ary[0]}{$ary[1]} = $q->param($fak)
if defined $ary[1];
}
my $ftext = '';
my $ei = scalar $q->param('FINDX');
for( my $i = 1; $i <= $ei; $i++ ) {
my $p = 'F' . $i . '_';
my $parcnt = $q->param($p.'L_PAREN');
$ftext .= ($parcnt < 1 ? '' : '('x$parcnt . ' ' );
if( defined $q->param($p.'FUNCT')
&& $q->param($p.'FUNCT') ne '' ) {
# TODO: Grab the $p.'ARG_' and Dump it.
my $f = $q->param($p.'FUNCT');
$f =~ s/\(\)\Z//;
my $args = '';
while (my ($k,$v) = each %{ $funct_args{$p} }) {
$args .= ',' if $args;
$v = "'".$v."'" if $v =~ /\W/;
$args .= "$k,$v";
}
$ftext .= " $f($args) ";
} else {
if( $q->param($p.'L_ISVAL') ) {
$ftext .= '\'' . $q->param($p.'L_VALUE') . '\'';
} else {
$ftext .= '[' . $q->param($p.'L_COLMN') . ']';
# force operator to be "like/not like" if a numeric operator
if ($o->typ4clm(uc($q->param($p.'L_COLMN'))) eq 'clob' &&
$q->param($p.'CMPOP') !~ /\w/) {
if ($q->param($p.'CMPOP') =~ /\!/) {
$q->param($p.'CMPOP', "not like");
} else {
$q->param($p.'CMPOP', "like");
}
}
}
$ftext .= ' ' . $q->param($p.'CMPOP') . ' ';
if( $q->param($p.'R_ISVAL') ) {
my $val = $q->param($p.'R_VALUE');
if ($val =~ /\'/ || $val =~ /\"/) {
if ($val !~ /\"/) { $val = '"'.$val.'"'; }
elsif ($val !~ /\'/) { $val = "'".$val."'"; }
else { $val =~ s/\'|\"//g; }
} else {
$val = "'$val'";
}
$ftext .= $val;
# if date comparison and right side is value and numeric operator
# ensure the right side valud fits date_format string
if ($q->param($p.'L_COLMN') &&
$q->param($p.'CMPOP') !~ /\w/ &&
exists $$o{schema}{select}{$q->param($p.'L_COLMN')} &&
exists $$o{schema}{select}{$q->param($p.'L_COLMN')}[3]{date_format}) {
my $date_format = $$o{schema}{select}{$q->param($p.'L_COLMN')}[3]{date_format};
local $$o{dbh}->{RaiseError} = 0;
local $$o{dbh}->{PrintError} = 0;
if ($$o{dbh}{Driver}{Name} eq 'Oracle') {
my $dt = $q->param($p.'R_VALUE');
if ($dt ne '') {
my ($rv) = $$o{dbh}->selectrow_array("SELECT 1 FROM dual WHERE to_date(?,'$date_format') IS NOT NULL", undef, $dt);
if (! $rv) {
$$o{error} = "invalid date: \"$dt\", must be in format: \"$date_format\"";
return undef;
}
}
}
}
} else {
$ftext .= '[' . $q->param($p.'R_COLMN') . ']';
}
}
$parcnt = $q->param($p.'R_PAREN');
$ftext .= ( $parcnt<1 ? '' : ')'x$parcnt .' ' ) . "\n";
$ftext .= $q->param($p.'ANDOR') . "\n" unless( $i == $ei );
}
$ftext =~ s/\n//g;
return $ftext;
}
# ------------------------- delselForm -------------------------
sub delselForm( $ ) {
my( $q ) = @_;
my $oei = scalar $q->param('FINDX');
my $ni=1;
for( my $oi = 1; $oi <= $oei; $oi++ ) {
my $op = 'F' . $oi . '_';
unless( $q->param($op.'DELME') ) {
if( $oi != $ni ){
my $np = 'F' . $ni . '_';
$q->delete($np.'FUNCT'); # clear so NOT assumed a func
foreach my $par ( $q->param() ) {
if( $par =~ s/\A$op// ){
$q->param( $np.$par, $q->param($op.$par) );
}
}
}
$ni++;
}
}
$ni--;
$q->param('FINDX', $ni);
return $oei - $ni;
}
# ------------------------- typ4clm -------------------------
sub typ4clm ($$) {
my( $o, $clm ) = @_;
$clm =~ s/\A\[//;
$clm =~ s/\]\Z//;
return $o->{oq}->get_col_types('filter')->{uc($clm)};
}
# ------------------------- cmpopLOV -------------------------
sub cmpopLOV { ['=','!=','<','<=','>','>=','like','not like','contains','not contains'] }
# ------------------------- html_parent_update -------------------------
sub html_parent_update( $ ) {
my ($o) = @_;
my $q = $o->{q};
my $filter = $q->param('filter');
$filter =~ s/\n/\ /g;
my $js = "
if( window.opener
&& !window.opener.closed
&& window.opener.OQval ) {
var w = window.opener;
w.OQval('filter', '".$o->escape_js($filter)."');
if (w.OQval('rows_page') == 'All') w.OQval('rows_page', 10);
w.OQrefresh();
window.close();
}
function show_defaultOQ() {
window.document.failedFilterForm.submit();
return true;
}
";
my $doc = $q->start_html( -title=>'OQFilter', -script=> $js )
. '<H3>Unable to contact this filters parent.</H3>'
. $q->start_form( -name=>'failedFilterForm', -class=>'filterForm', -action => $$o{schema}{URI_standalone});
if (ref($$o{schema}{state_params}) eq 'ARRAY') {
foreach my $p (@{ $$o{schema}{state_params} }) {
$doc .= "<input type='hidden' name='$p' value='".$o->escape_html($q->param($p))."'>";
}
}
$doc .= $q->hidden( -name=>'filter', -value=>'')
. '<A HREF="" onclick="show_defaultOQ();return false;">'
. 'Click here for a default view</A> of the following RAW filter.'
. '<HR /><PRE>'
. $o->escape_html( $q->param('filter') )
. '</PRE><HR />'
. $q->end_html() ;
return $doc;
}
# ------------------------- getFunctionNames -------------------------
sub getFunctionNames( $ ) {
my( $o ) = @_;
my %functs = (); # ( t1=>'Test One', t2=>"Test Two" );
foreach my $k ( keys %{$o->{schema}->{'named_filters'}} ) {
my $fref = $o->{schema}->{'named_filters'}{$k};
if (ref $fref eq 'ARRAY') { $functs{"$k".'()'} = $fref->[2]; }
elsif (ref $fref eq 'HASH' && $fref->{'title'} ne '') {
$functs{"$k".'()'} = $fref->{'title'};
}
}
return %functs;
}
# ------------------------- getColumnNames -------------------------
sub getColumnNames( $ ) {
my( $o ) = @_;
my %cols = (); # ( t1=>'Test One', t2=>"Test Two" );
foreach my $k ( keys %{$o->{schema}->{'select'}} ) {
next if $$o{schema}{select}{$k}[3]{is_hidden};
my $cref = $o->{schema}->{'select'}{$k};
$cols{"$k"} =
( ref $cref eq 'ARRAY' ) ? $cref->[2] : 'bad:'.(ref $cref) ;
}
return %cols;
}
# ------------------------- html_filter_form -------------------------
sub html_filter_form( $ ) {
my( $o ) = @_;
my %columnLBL = $o->getColumnNames();
my @columnLOV = sort { $columnLBL{$a} cmp $columnLBL{$b} } keys %columnLBL;
# TODO: create named_functions from pre-exising filters and use them
# my @functionLOV = map {"$_".'()'} keys %{$o->{schema}->{'named_filters'}};
# my @functionLOV = keys %{$o->{schema}->{'named_filters'}};
my %functionLBL = $o->getFunctionNames();
my @functionLOV = sort { $functionLBL{$a} cmp $functionLBL{$b} } keys %functionLBL;
# (t1=>'Test One', t2=>"Test Two");
my @andorLOV = ('AND', 'OR');
my $js="
function toggle_value(basenam) {
var f = window.document.filterForm;
if( f.elements[basenam+'ISVAL'].value ) {
f.elements[basenam+'ISVAL'].value = '';
f.elements[basenam+'BTN'].value = 'column:';
f.elements[basenam+'VALUE'].className = 'hide';
f.elements[basenam+'COLMN'].className = 'col';
} else {
f.elements[basenam+'ISVAL'].value = 1;
f.elements[basenam+'BTN'].value = 'value:';
f.elements[basenam+'VALUE'].className = 'val';
f.elements[basenam+'COLMN'].className = 'hide';
}
return true;
}
function update_paren_vis(basenam) {
var f = window.document.filterForm;
if( f.elements[basenam+'PAREN'].options[0].selected ) {
f.elements[basenam+'PARBTN'].className = 'noparen';
f.elements[basenam+'PAREN'].className = 'hide';
} else {
f.elements[basenam+'PARBTN'].className = 'hide';
f.elements[basenam+'PAREN'].className = 'paren';
}
window.check_paren();
return true;
}
function toggle_paren(basenam) {
var f = window.document.filterForm;
if( f.elements[basenam+'PAREN'].options[0].selected ) {
f.elements[basenam+'PAREN'].options[1].selected = true;
} else {
f.elements[basenam+'PAREN'].options[0].selected = true;
}
window.update_paren_vis(basenam);
return true;
}
function show_submit_del() {
var f = window.document.filterForm;
var i = f.elements['FINDX'].value;
for(; i>0; i--){
if( f.elements['F'+i+'_DELME'].checked ) {
f.elements['SUBMIT_DEL'].className = 'delbtn';
window.document.getElementById('submit_text').className = 'submit_off';
window.document.getElementById('submit_add').className = 'add_off';
return true;
}
}
f.elements['SUBMIT_DEL'].className = 'hide';
f.elements['CHECKALL'].checked = false;
window.document.getElementById('submit_add').className = 'add_ok';
window.check_paren();
return true;
}
function submit_act(actval) {
var f = window.document.filterForm;
f.elements.act.value = actval;
f.submit();
return true;
}
function checkall_delme() {
var f = window.document.filterForm;
var newval = f.elements['CHECKALL'].checked;
var i = f.elements['FINDX'].value;
for(; i>0; i--){
f.elements['F'+i+'_DELME'].checked = newval;
}
window.show_submit_del();
return true;
}
function check_paren() {
var f = window.document.filterForm;
var i = f.elements['FINDX'].value;
var ocnt = 0;
for(; i>0; i--){
ocnt += f.elements['F'+i+'_R_PAREN'].value - f.elements['F'+i+'_L_PAREN'].value;
if( ocnt < 0 ) {
i = -3;
}
}
if( ocnt == 0 ) {
window.document.getElementById('submit_text').className = 'submit_ok';
window.document.getElementById('paren_warn').className = 'paren_match';
} else {
window.document.getElementById('submit_text').className = 'submit_off';
window.document.getElementById('paren_warn').className = 'paren_warn';
}
return true;
}
";
my $q = $o->{q};
# pull out the fuctions arguments from the form
my %funct_args = ();
foreach my $fak ( $q->param() ){
my @ary = split 'ARG_', $fak;
$funct_args{$ary[0]}{$ary[1]} = $q->param($fak)
if defined $ary[1];
}
my $html =
$q->start_html ( -title=>"Interactive Filter - $$o{schema}{title}",
-script=> $js,
-head=>
$$o{schema}{options}{'CGI::OptimalQuery::InteractiveFilter'}{css} ).
"<center>".
(($$o{error}) ? "<strong>".$q->escapeHTML($$o{error})."</strong>" : "").
$q->start_form ( -action=> $$o{schema}{URI_standalone}, -name=>'filterForm',
-class=>'filterForm');
if (ref($$o{schema}{state_params}) eq 'ARRAY') {
foreach my $p (@{ $$o{schema}{state_params} }) {
$html .= "<input type='hidden' name='$p' value='".$o->escape_html($q->param($p))."'>";
}
}
$html .=
$q->hidden ( -name=>'module', -value=>'InteractiveFilter',
-override=>1 )
. $q->hidden ( -name=>'act', -value=>'submit_filter',
-override=>1 )
. $q->hidden ( -name=>'hideParen', -value=>1 )
. $q->hidden ( -name=>'FINDX', -value=>'0') ;
$html .= "<TABLE COLUMNS=6>\n";
my $hideParen = $q->param('hideParen');
my $pnp; # parameter name prefix
my $thing_to_focus_on;
for( my $findx = 1; $findx <= $q->param('FINDX'); $findx++ ) {
$pnp = 'F' . $findx . '_';
$html .= '<TR><TD class="lp_col">'
. $q->button ( -name=>$pnp.'L_PARBTN', -label=>'(',
-onClick=>"toggle_paren('$pnp"."L_');",
-class=> $hideParen
? 'hide' : ( $q->param($pnp.'L_PAREN') > 0
? 'hide' : 'noparen' ) )
. $q->popup_menu
( -name=>$pnp.'L_PAREN', -values=>[0 .. 3], -default=>'0',
-labels=>{'0'=>'','1'=>'(','2'=>'((','3'=>'((('},
-onChange=>"update_paren_vis('$pnp"."L_');",
-class=>$q->param($pnp.'L_PAREN')<1 ?'hide':'paren' )
. '</TD>';
if( defined $q->param($pnp.'FUNCT') ) {
my $func_nam = $q->param($pnp.'FUNCT');
$func_nam =~ s/\(\)//;
# if a predefined named filter
if (ref($o->{schema}->{'named_filters'}{$func_nam}) eq 'ARRAY') {
$html .= '<TD class="f_col" colspan=3>'
. $q->popup_menu( -name=>$pnp.'FUNCT',
-values=> \ @functionLOV,
-labels=> \ %functionLBL,
-default=> $q->param($pnp.'FUNCT'),
-onChange=>"submit_act('refresh');" ) ;
$html .= '</TD>';
}
# if named filter has an html generator
elsif (exists $o->{schema}->{'named_filters'}{$func_nam}{html_generator}) {
$html .= '<TD class="f_col" colspan=3>'
. $q->popup_menu( -name=>$pnp.'FUNCT',
-values=> \ @functionLOV,
-labels=> \ %functionLBL,
-default=> $q->param($pnp.'FUNCT'),
-onChange=>"submit_act('refresh');" ) ;
$html .=
$o->{schema}->{'named_filters'}{$func_nam}{'html_generator'}->($q, $pnp.'ARG_');
$html .= '</TD>';
}
# else if named filter does not have a html_generator
else {
$html .= "<TD class='f_col' colspan=3><input type=hidden name='$pnp"."FUNCT' value='".$o->escape_html("$func_nam()")."' />";
my %args;
my $arg_prefix = quotemeta($pnp.'ARG_');
foreach my $param (grep { /^$arg_prefix/ } $q->param) {
my $k = $param; $k =~ s/$arg_prefix//;
my $v = $q->param($param);
$args{$k} = $v;
$html .= "<input type=hidden name='$param' value='".$o->escape_html($q->param($param))."' />";
}
my $rv = $o->{schema}->{'named_filters'}{$func_nam}{'sql_generator'}->(%args);
$html .= "<div class=RO_NAMED_FILTER>".$o->escape_html($$rv[2])."</div></TD>";
}
}
else {
$html .= '<TD class="l_col">'
. &cmp_val($q, $pnp.'L_', \ @columnLOV, \ %columnLBL)
. '</TD><TD class="c_col">'
. $q->popup_menu (
-name=>$pnp.'CMPOP', -values=> cmpopLOV(), -class=>'cmpop')
. '</TD><TD class="r_col">'
. &cmp_val($q, $pnp.'R_', \ @columnLOV, \ %columnLBL )
. '</TD>';
}
$html .= '<TD class="rp_col">'
. $q->popup_menu ( -name=>$pnp.'R_PAREN',
-values=>[0 .. 3], -default=>'0',
-labels=>
{'0'=>'', '1'=>')', '2'=>'))', '3'=>')))'},
-onChange=>"update_paren_vis('$pnp"."R_');",
-class=> ( $q->param($pnp.'R_PAREN')<1
? 'hide' : 'paren' ) )
. $q->button ( -name=>$pnp.'R_PARBTN', -label=>')',
-onClick=>"toggle_paren('$pnp"."R_');",
-class=> $hideParen
? 'hide'
: ( $q->param($pnp.'R_PAREN')>0
? 'hide' : 'noparen') )
. '</TD><TD class="d_col">'
. $q->checkbox ( -name=>$pnp.'DELME', -label=>'remove',
-value=>'1', -checked=>0, -override=>1,
-onClick=>'show_submit_del();',
-class=>'delbox' )
. "</TD></TR>\n<TR><TD colspan=5 align=center>"
. $q->popup_menu ( -name=>$pnp.'ANDOR', -values=> \ @andorLOV,
-class=>$findx == $q->param('FINDX')?'hide':'')
. "</TD></TR>\n" ;
}
$html .= '<TR><TD colspan=5><HR width="90%" /></TD><TD class="d_col">'
. $q->checkbox ( -name=>'CHECKALL', -label=>'ALL', -value=>'1',
-checked=>0, -override=>1,
-onClick=>'checkall_delme();',
-class=>'delbox' )
. '</TD></TR> <TR class="footer"><TD colspan=5></TD><TD class="d_col">'
. $q->button ( -name=>'SUBMIT_DEL', -label=>'REMOVE',
-onClick=>"submit_act('submit_del');",
-class=> 'hide' )
. '</TD></TR>'
if( $q->param('FINDX') > 0 ); # we printed something above here
my @sel_opts = ('-- add new filter element --', $q->optgroup ( -name=>'Column to compare:',
-values=> \ @columnLOV ,
-labels=> \ %columnLBL ) );
if (@functionLOV) {
push @sel_opts, $q->optgroup ( -name=>'Named Filters:',
-values=> \ @functionLOV ,
-labels=> \ %functionLBL );
}
$html .= "</TABLE>\n"
. '<DIV id="paren_warn" class="paren_match">( Parenthesis must be matching pairs )</DIV>'
. '<SPAN id="submit_add" class="submit_ok">'
. $q->popup_menu ( -name=>'NEXT_EXPR',
-default=>'--- Choose Next Filter ---',
-override=>1,
-values=>\@sel_opts,
-onChange=>"submit();" )
. '</SPAN><SPAN id="submit_text" class="submit_ok"> or '
. $q->submit( -name=>'SUBMIT', -class=>'submit_ok' )
. "</SPAN> "
. $q->end_form()
. "\n</center>
<script type='text/javascript'>
check_paren();
if (window.document.forms[0].elements['F".$q->param('FINDX')."_R_VALUE'])
window.document.forms[0].elements['F".$q->param('FINDX')."_R_VALUE'].focus();
</script><noscript>Javascript is required when viewing this page.</noscript>
".$q->end_html();
return $html;
}
1;
| gitpan/CGI-OptimalQuery | lib/CGI/OptimalQuery/InteractiveFilter.pm | Perl | mit | 26,877 |
=head1 NAME
INSTALL - Swish-e Installation Instructions
=head1 OVERVIEW
This document describes how to download, build,
and install Swish-e from source.
Also found below is a basic overview of using Swish-e to index documents,
with pointers to other, more advanced examples.
This document also provides instructions
on how to get help installing and using Swish-e
(and the important information you should provide when asking for help).
Please read these instructions B<before requesting help>
on the Swish-e discussion list.
See L<"QUESTIONS AND TROUBLESHOOTING">.
Although building from source is recommended,
some OS distributions (e.g., Debian) provide pre-compiled binaries.
Check with your distribution for available packages.
Build from source,
if your distribution does not offer the current version of Swish-e.
Also, please read the Swish-e FAQ (L<SWISH-FAQ|SWISH-FAQ>),
as it answers many frequently-asked questions.
Swish-e knows how to index HTML, XML, and plain text documents.
Helper applications and other tools are used to convert documents
such as PDF or MS Word into a format that Swish-e can index.
These additional applications and tools (listed below)
must be installed separately.
The process of converting documents is called "filtering".
NOTE: Swish-e version 4.2.0 installs a lot more files
when running "make install".
Be aware that the Swish-e documentation may thus include errors
about where files are located.
Please notify the Swish-e discussion list of any documentation errors.
=head2 Upgrading from previous versions of Swish-e
If you are upgrading from a previous version of Swish-e,
read the L<CHANGES|CHANGES> page first.
The Swish-e index format may have changed
and existing indexes may not work with the newer version of Swish-e.
If you have existing indexes,
you may need to re-index your data
before running the "make install" step described below.
Swish-e may be run from the build directory after compiling,
but before installation.
=head2 Windows Users
A Windows binary version is available
as a separate download from the Swish-e site (http://swish-e.org).
Many of the installation instructions below will not apply to Windows users;
the Windows version is pre-compiled
and includes F<libxml2>, F<zlib>, F<xpdf>, and F<catdoc>.
A number of Perl modules may also be needed.
These can be installed with ActiveState's PPM utility.
libwww-perl - the LWP modules (for spidering)
HTML-Tagset - used by web spider
HTML-Parser - used by web spider
MIME-Types - used for filtering documents when not spidering
HTML-Template - formatting output from swish.cgi (optional)
HTML-FillInForm (if HTML-Template is used)
=head2 Building from CVS
Please refer to the F<README.cvs> file found in the documentation directory
F<$prefix/share/doc/swish-e>.
=head1 SYSTEM REQUIREMENTS
Swish-e makes use of a number of libraries and tools
that are not distributed with Swish-e.
Some libraries need to be installed before building Swish-e from source;
other tools can be installed at any time.
See below for details.
=head2 Software Requirements
Swish-e is written in C.
It has been tested on a number of platforms,
including Sun/Solaris, Dec Alpha, BSD, Linux, Mac OS X, and Open VMS.
The GNU C compiler (gcc) and GNU make are strongly recommended.
Repeat: you will find life easier if you use the GNU tools.
=head2 Optional but Recommended Packages
Most of the packages listed below are available
as easily installable packages.
Check with your operating system vendor or install them from source.
Most are very common packages that may already be installed on your computer.
As noted below,
some packages need to be installed before building Swish-e from source,
while others may be added after Swish-e is installed.
=over 4
=item * Libxml2
F<libxml2> is very strongly recommended.
It is used for parsing both HTML and XML files.
Swish-e can be built and installed without F<libxml2>,
but the HTML parser that is built into Swish-e
is not as accurate as F<libxml2>.
http://xmlsoft.org/
F<libxml2> must be installed before Swish-e is built,
or it will not be used.
If F<libxml2> is installed in a non-standard location
(e.g., F<libxml2> is built with C<--prefix $HOME/local>),
make sure that you add the C<bin> directory to your C<$PATH>
before building Swish-e.
Swish-e's configure script uses a program
created by F<libxml2> (C<xml2-config>)
to find the location of F<libxml2>.
Use C<which xml2-config> to verify
that the program can be found where expected.
=item * Zlib Compression
The F<Zlib> compression library is commonly installed on most systems
and is recommended for use with Swish-e.
F<Zlib> is used for compressing text stored in the Swish-e index.
http://www.gzip.org/zlib/
F<Zlib> must be installed before building Swish-e.
=item * Perl Modules
Although Swish-e is a compiled C program,
many support features use Perl.
For example, both the web spiders
and modules to help with filtering documents are written in Perl.
The following Perl modules may be required.
Check your current Perl installation,
as many may already be installed.
LWP
URI
HTML::Parser
HTML::Tagset
MIME::Types (optional)
Note that installing C<Bundle::LWP> with the CPAN module
perl -MCPAN -e 'install Bundle::LWP'
will install many of the above modules.
If you wish to use C<HTML-Template> with swish.cgi to generate output,
install:
HTML::Template
HTML::FillInForm
If you wish to use C<Template-Toolkit> with C<swish.cgi>
to generate output, install:
Template
Questions about installing these modules
may be sent to the Swish-e discussion list.
The C<search.cgi> example script
requires both C<Template-Toolkit> and C<HTML::FillInForm>.
=item * Indexing PDF Documents
Indexing PDF files requires the C<xpdf> package.
This is a common package,
available with most operating systems
and often provided as an add-on package.
http://www.foolabs.com/xpdf/
Xpdf may be added after Swish-e is installed.
=item * Indexing MS Word Documents
Indexing MS Word documents requires the F<Catdoc> program.
http://www.wagner.pp.ru/~vitus/software/catdoc/
F<Catdoc> may be added after Swish-e is installed.
=item * Indexing MP3 ID3 Tags
Indexing MP3 ID3 Tags requires the C<MP3::Tag> Perl module.
See http://search.cpan.org.
C<MP3::Tag> may be installed after Swish-e is installed.
=item * Indexing MS Excel Files
Indexing MS Excel files is supported by the following Perl modules,
also available at http://search.cpan.org.
Spreadsheet::ParseExcel
HTML::Entities
These Perl modules may be installed after Swish-e is installed.
=back
=head1 INSTALLATION
Here are brief installation instructions that should work in most cases.
Following this section are more detailed instructions and examples.
=head2 Building Swish-e
Download Swish-e using your favorite web browser
or a utility such as C<wget>, C<lynx>, or C<lwp-download>.
Unpack and build the distribution, using the following steps:
Note: "swish-e-2.4.0" is used as an example.
Download the most current available version
and adjust the commands below!
Also, if you are running Debian,
see the notes below on building a C<.deb> package
from the Swish-e source package.
Pay careful attention to the "prompt" character used
on the following command lines.
A "$" prompt indicates steps run as an unprivileged user.
A "#" indicates steps run as the superuser (root).
$ wget http://swish-e.org/Download/swish-e-2.4.0.tar.gz
$ gzip -dc swihs-e-2.4.0.tar.gz | tar xof -
$ cd swish-e-2.4.0 (this directory will depend on the version of Swish-e)
$ ./configure
$ make
$ make check
...
==================
All 3 tests passed
==================
$ su root (or use sudo)
(enter password)
# make install
# exit
$ swish-e -V
SWISH-E 2.4.0
B<IMPORTANT:>
Once Swish-e is installed, do not run it as the superuser (root) --
root is only required during the installation step,
when installing into system directories.
Please do not break this rule.
B<NOTE:>
If you are upgrading from an older version of Swish-e,
be sure and review the L<CHANGES|CHANGES> file.
Old index files may not be compatible with newer versions of Swish-e.
After building Swish-e (but before running "make install"),
Swish-e can be run from the build directory:
$ src/swish-e -V
To minimize downtime,
create new index files before running "make install",
by using Swish-e from the build directory.
Then, copy the index files to the live location and run "make install":
$ src/swish-e -c /path/to/config -f index.new
Keep in mind that the location you index from
may affect the paths stored in the index file.
=head2 Installing without root access
Here's another installation example.
This might be used if you do not have root access
or you wish to install Swish-e someplace other than C</usr/local>.
This example also shows building Swish-e in a "build" directory
that is separate from where the source files are located.
This is the recommended way to build Swish-e,
but it requires GNU Make.
Without GNU Make,
you will likely need to build from within the source directory,
as shown in the previous example.
$ tar zxof swish-e-2.4.0.tar.gz (GNU tar with "z" option)
$ mkdir build
$ cd build
Note that the current directory is not where Swish-e was unpacked.
Swish-e uses a F<configure> script.
F<configure> has many options,
but it uses reasonable and standard defaults.
Running
$ ../swish-e-2.4.0/configure --help
will display the options.
Two options are of common interest:
C<--prefix> sets the top-level installation directory;
C<--disable-shared> will link Swish-e statically,
which may be needed on some platforms (Solaris 2.6, perhaps).
Platforms may require varying link instructions
when libraries are installed in non-standard locations.
Swish-e uses the GNU F<autoconf> tools for building the package.
F<autoconf> is good at building and testing,
but still requires you to provide information appropriate for your platform.
This may mean reading the manual page for your compiler and linker
to see how to specify non-standard file locations.
For most Unix-type platforms,
you can use C<LDFLAGS> and C<CPPFLAGS> environment variables
to specify paths to "include" (header) files
and to libraries that are not in standard locations.
In this example, we do not have root access.
We have installed F<libxml2> and F<libz> in C<$HOME/local>.
Swish-e will also be installed in C<$HOME/local>
(by using the C<--prefix> setting).
In this case,
you would need to add C<$HOME/local/bin>
to the start of your shell's C<$PATH> setting.
This is required because F<libxml2> installs a program
that is used when running the configure script.
Before running configure, type:
$ which xml2-config
It should list C<$HOME/local/bin/xml2-config>.
Now run F<configure> (remember, we are in a separate "build" directory):
$ ../swish-e-2.4.0/configure \
--prefix=$HOME/local \
CPPFLAGS=-I$HOME/local/include \
LDFLAGS="-R$HOME/local/lib -L$HOME/local/lib"
$ make >/dev/null (redirect output to only see warnings and errors)
$ make check
...
==================
All 3 tests passed
==================
$ make install
$ $HOME/local/bin/swish-e -V
SWISH-E 2.4.0
Note the use of double quotes in the C<LDFLAGS> line above.
This allows C<$HOME> to be expanded within the text string.
=head2 Run-time paths
The C<-R> option says to add a specified path (or paths)
to those that are used to find shared libraries at run time.
These paths are stored in the Swish-e binary.
When Swish-e is run,
it will look in these directories for shared libraries.
Some platforms may not support the C<-R> option.
In this event,
set the C<LD_RUN_PATH> environment variable B<before> running make.
Some systems, such as Redhat,
do not look in C</usr/local/lib> for libraries.
In these cases,
you can either use C<-R>, as above, when building Swish-e
or add C</usr/local/lib> to C</etc/ld.so.conf> and run F<ldconfig> as root.
If all else fails,
you may need to actually read the man pages for your platform.
=head2 Building a Debian Package
The Swish-e distribution includes the files required
to build a Debian package.
$ tar zxof swish-e-2.4.0.tar.gz (GNU tar with "z" option)
$ cd swish-e-2.4.0
$ fakeroot debian/rules binary
[lots of output]
dpkg-deb: building package `swish-e' in `../swish-e_2.4.0-0_i386.deb'.
$ su
# dpkg -i ../swish-e_2.4.0-0_i386.deb
=head2 What's installed
Swish installs a number of files.
By default, all files are installed below C</usr/local>,
but this can be changed by setting C<--prefix>
when running F<configure> (as shown above).
Individual paths may also be set.
Run C<configure --help> for details.
$prefix/bin/swish-e The Swish-e binary program
$prefix/share/doc/swish-e/ Full documentation and examples
$prefix/lib/libswish-e The Swish-e C library
$prefix/include/swish-e.h The library header file
$prefix/man/man1/ Documentation as manual pages
$prefix/lib/swish-e/ Helper programs (spider.pl, swishspider, swish.cgi)
$prefix/lib/swish-e/perl/ Perl helper modules
Note that the Perl modules are I<not> installed in the system Perl library.
Swish-e and the Perl scripts that require the modules
know where to find the modules,
but the F<perldoc> program (used for reading documentation) does not.
This can be corrected by adding C<$prefix/lib/swish-e>
and C<$prefix/lib/swish-e/perl> to the C<PERL5LIB> environment variable.
=head2 Documentation
Documentation can be found in the C<$prefix/share/doc/swish-e> directory.
Documentation is in html format at C<$prefix/share/doc/swish-e/html> and
can also be read on-line at the Swish-e web site:
http://swish-e.org/
=head2 The Swish-e documentation as man(1) pages
Running "make install" installs some of the Swish-e documentation as man pages.
The following man pages are installed:
SWISH-FAQ(1)
SWISH-CONFIG(1)
SWISH-RUN(1)
SWISH-LIBRARY(1)
The man pages are installed, by default, in the system man directory.
This directory is determined when F<configure> is run;
it can be set by passing a directory name to F<configure>.
For example,
./configure --mandir=/usr/local/doc/man
The man directory is specified relative to the C<--prefix> setting.
If you use C<--prefix>,
you do not normally need to also specify C<--mandir>.
Information on running F<configure> can be found by typing:
./configure --help
=head2 Join the Swish-e discussion list
The final step, when installing Swish-e,
is to join the Swish-e discussion list.
The Swish-e discussion list is the place
to ask questions about installing and using Swish-e,
see or post bug fixes or security announcements,
and offer help to others.
Please do not contact the developers directly.
The list is typically I<very low traffic>,
so it won't overload your inbox.
Please take the time to subscribe.
See http://Swish-e.org.
If you are using Swish-e on a public site,
please let the list know,
so that your URL can be added to the list of sites that use Swish-e!
Please review the next section
before posting questions to the Swish-e list.
=head1 QUESTIONS AND TROUBLESHOOTING
Support for installation, configuration, and usage
is available via the Swish-e discussion list.
Visit http://swish-e.org for information.
Do not contact developers directly for help --
always post your question to the list.
It's very important to provide the right information
when asking for help.
Please search the Swish-e list archive before posting a question.
Also, check the L<SWISH-FAQ|SWISH-FAQ>
to see if your question has already been asked and answered.
Before posting, use the available tools to narrow down the problem.
Swish-e has several switches
(e.g., C<-T>, C<-v>, and C<-k>)
that may help you resolve issues.
These switches are described on the L<SWISH-RUN|SWISH-RUN> page.
For example, if you cannot find a document by a keyword
that you believe should be indexed,
try indexing just that single file
and use the C<-T INDEXED_WORDS> option
to see if the word is actually being indexed.
First, try it without any changes to default settings:
swish-e -i testdoc.html -T indexed_words | less
if that works, add in your configuration file:
swish-e -i testdoc.html -c swish.conf -T indexed_words | less
If it still isn't working as you expect,
try to reduce the test document to a very small example.
This will be very helpful to your readers,
when you are asking for help.
Another useful trick is to use C<-H9> when searching,
to display full headers in search results.
Look at the "Parsed Words" header
to see what words Swish-e is searching for.
=head2 When posting, please provide the following information:
Use these guidelines when asking for help.
The most important tip is to provide the B<least> amount of information
that can be used to reproduce your problem.
Do not paraphrase output -- copy-and-paste --
but trim text that is not necessary.
=over 4
=item *
The exact version of Swish-e that you are using.
Running Swish-e with the C<-V> switch will print the version number.
Also, supply the output from C<uname -a> or similar command
that identifies the operating system you are running on.
If you are running an old version of swish,
be prepared for a response of "upgrade" to your question.
=item *
A summary of the problem.
This should include the commands issued
(e.g. for indexing or searching) and their output,
along with an explanation of why you don't think it's working correctly.
Please copy-and-paste the exact commands and their output,
instead of retyping, to avoid errors.
=item *
Include a copy of the configuration file you are using, if any.
Swish-e has reasonable defaults,
so in many cases you can run it without using a configuration file.
But, if you need to use a configuration file,
B<reduce it down> to the absolute minimum number of commands
that is required to demonstrate your problem.
Again, copy-and-paste.
=item *
A small copy of a source document that demonstrates the problem.
If you are having problems spidering a web server,
use lwp-download or wget to copy the file locally,
then make sure you can index the document using the file system method.
This will help you determine if the problem
is with spidering or indexing.
If you expect help with spidering,
don't post fake URLs, as it makes it impossible to test.
If you don't want to expose your web page to the people on the Swish-e list,
find some other site to test spidering on.
If that works, but you still cannot spider your own site,
you may need to request help from others.
If so, you must post your real URL
or make a test document available via some other source.
=item *
If you are having trouble building Swish-e,
please copy-and-paste the output from make
(or from C<./configure>, if that's where the problem is).
=back
The key is to provide enough information
so that others may reproduce the problem.
=head1 ADDITIONAL INSTALLATION OPTIONS
These steps are not required for normal use of Swish-e.
=head2 The SWISH::API Perl Module
The Swish-e distribution includes a module
that provides a Perl interface to the Swish-e C library.
This module provides a way to search a Swish-e index
without running the Swish-e program.
Searching an index will be many times faster
when running under a persistent environment
such as Apache/mod_perl with the C<SWISH::API> module.
See the F<perl/README> file for information
on installing and using the C<SWISH::API> Perl module.
=head1 GENERAL CONFIGURATION AND USAGE
This section should give you a basic overview
of indexing and searching with B<Swish-e>.
Other examples can be found in the C<conf> directory;
these will step you through a number of different configurations.
Also, please review the L<SWISH-FAQ|SWISH-FAQ>.
Swish-e is a command-line program.
The program is controlled by passing switches on the command line.
A configuration file may be used,
but often is not required.
Swish-e does not include a graphical user interface.
Example CGI scripts are provided in the distribution,
but they require additional setup to use.
=head2 Introduction to Indexing and Searching
Swish-e can index files that are located on the local file system.
For example, running:
swish-e -i /var/www/htdocs
will index I<all> files in the C</var/www/htdocs> directory.
You may specify one or more files or directories with the C<-i> option.
By default, this will create an index called C<index.swish-e>
in the current directory.
To search the resulting index for a given word, try:
swish-e -w apache
This will find the word "apache" in the body or title
of the indexed documents.
As mentioned above,
Swish-e will index all files in a directory,
unless instructed otherwise.
So, if C</var/www/htdocs> contains non-HTML files,
you will need a configuration file to limit the files that Swish-e indexes.
Create a file called C<swish.conf>:
# Example configuration file
# Tell Swish-e what to index (same as -i switch above)
IndexDir /var/www/htdocs
# Only index HTML and text files
IndexOnly .htm .html .txt
# Tell Swish-e that .txt files are to use the text parser.
IndexContents TXT* .txt
# Otherwise, use the HTML parser
DefaultContents HTML*
# Ask libxml2 to report any parsing errors and warnings or
# any UTF-8 to 8859-1 conversion errors
ParserWarnLevel 9
After saving the configuration file, reindex:
swish-e -c swish.conf
The Swish-e configuration settings are described
in the L<SWISH-CONFIG|SWISH-CONFIG> manual page.
The order of statements in the configuration file is typically not important,
although some statements depend on previously set statements.
There are many possible settings.
Good advice is to use as few settings as possible
when first starting out with Swish-e.
The runtime options (switches) are described
in the L<SWISH-RUN|SWISH-RUN> manual page.
You may also see a summary of options by running:
swish-e -h
Swish-e has two other methods for reading input files.
One method uses a Perl helper script and the LWP Perl library
to spider remote web sites:
swish-e -S http -i http://localhost/index.html -v2
This will spider the web server running on the local host.
The C<-S> option defines the input source method to be "http",
C<-i> specifies the URL to spider,
and C<-v> sets the verbose level to two.
There are a number of configuration options
that are specific to the C<-S> http input source.
See L<SWISH-CONFIG|SWISH-CONFIG>.
Note that only files of C<Content-Type text/*> will be indexed.
The C<-S http> method is deprecated, however,
in favor of a variation on the following input method.
There is a general-purpose input method
wherein Swish-e reads input from a program
that produces documents in a special format.
The program might read and format data stored in a database,
or parse and format messages in a mailing list archive,
or run a program that spiders web sites (like the previous method).
The Swish-e distribution includes a spider program
that uses this method of input.
This spider program is much more configurable and feature-rich
than the previous (C<-S http>) method.
To duplicate the previous example,
create a configuration file called C<swish2.conf>:
# Example for spidering
# Use the "spider.pl" program included with Swish-e
IndexDir spider.pl
# Define what site to index
SwishProgParameters default http://localhost/index.html
Then, create the index using the command:
swish-e -S prog -c swish2.conf
This says to use the C<-S prog> input source method.
Note that, in this case,
the C<IndexDir> setting does not specify a file or directory to index,
but a program name to be run.
This program, C<spider.pl>,
does the work of fetching the documents from the web server
and passing them to Swish-e for indexing.
The C<SwishProgParameters> option is a special feature
that allows passing command-line parameters
to the program specified with C<IndexDir>.
In this case, we are passing the word C<default>
(which tells C<spider.pl> to use default settings)
and the URL to spider.
Running a script under Windows requires specifying the interpreter
(e.g., C<perl.exe>)
and then using C<SwishPropParameters>
to specify the script and the script's parameters.
See I<Notes when using C<-S prog> on MS Windows>
on the L<SWISH-RUN|SWISH-RUN> page.
The advantage of the C<-S prog> method of spidering
(over the previous C<-S http> method)
is that the Perl code is only compiled once
instead of once for every document fetched from the web server.
In addition, it is a much more advanced spider with many, many features.
Still, as used here,
C<spider.pl> will automatically index PDF or MS Word documents
if (when) Xpdf and Catdoc are installed.
A special form of the C<-S prog> input source method is:
./myprog --option | swish-e -S prog -i stdin -c config
This allows running Swish-e from a program
(instead of running the external program from Swish-e).
So, this also can be done as:
./myprog --option > outfile
swish-e -S prog -i stdin -c config < outfile
or
./myprog --option > outfile
cat outfile | swish-e -S prog -i stdin -c config
One final note about the C<-S prog> input source method.
The program specified with C<-i> or C<IndexDir> needs to be an absolute path.
The exception is when the program is installed in the C<libexecdir> directory.
Then, a plain program name may be specified
(as in the example showing C<spider.pl>, above).
All three input source methods are described in more detail
on the L<SWISH-RUN|SWISH-RUN> page.
=head2 Metanames and Properties
There are two key Swish-e concepts
that you need to be familiar with:
Metanames and Properties.
=over 4
=item * Metanames
Swish-e creates a reverse (i.e., inverted) index.
Just like an index in a book,
you look up a word and it lists the pages (or documents)
where that word can be found.
Swish-e can create multiple index tables within the same index file.
For example,
you might want to create an index that only contains words in HTML titles,
so that searches can be limited to title text.
Or, you might have descriptive words
that you would like to search,
stored in a meta tag called "keywords".
Some database systems might call these different "fields" or "columns",
but Swish-e calls them I<MetaNames>
(as a result of its first indexing HTML "meta" tags).
To find documents containing "foo" in their titles, you might run:
swish-e -w swishtitle=foo
or, a more advanced example:
swish-e -w swishtitle=(foo or bar) or swishdefault=(baz)
The Metaname "swishdefault" is the name that is used by Swish-e
if no other name is specified.
The following two searches are thus equivalent:
swish-e -w foo
swish-e -w swishdefault=foo
When indexing HTML documents,
Swish-e indexes words in the body and title
under the Metaname "swishdefault".
=item * Properties
Swish-e's search result is a list of files --
actually, Swish-e uses file numbers internally.
Data can be associated with each file number when indexing.
For example, by default Swish-e associates the file's name, title,
last modified date, and size with the file number.
These items can be printed in search results.
In Swish-e, this associated data is called a file's I<Properties>.
Properties can be any data you wish to associated with a document --
in fact, the entire text of the document can be stored in the index.
What data is stored as a Property is controlled by the I<PropertyNames>
(and other) configuration directives.
What properties are printed with search results
depends on the C<-x> or C<-p> switches.
By default,
Swish-e returns the rank, path/URL, title, and file size in bytes
for each result.
=back
=head2 Getting Started With Swish-e
Swish-e reads a configuration file (see L<SWISH-CONFIG|SWISH-CONFIG>)
for directives that control whether and how Swish-e indexes files.
Swish-e is also controlled by command-line arguments
(see L<SWISH-RUN|SWISH-RUN>).
Many of the command-line arguments
have equivalent configuration directives (e.g., C<-i> and C<IndexDir>).
Swish-e does not require a configuration file,
but most people change its default behavior
by placing settings in a configuration file.
To try the examples below,
go to the C<tests> subdirectory of the distribution.
The tests will use the C<*.html> files in this directory
when creating the test index.
You may wish to review these C<*.html> files
to get an idea of the various native file formats that Swish-e supports.
You may also use your own test documents.
It's recommended to use small test documents when first using Swish-e.
=head2 Step 1: Create a Configuration File
The configuration file controls what and how Swish-e indexes. The
configuration file consists of directives, comments, and blank lines.
The configuration file can be any name you like.
This example will work with the documents in the F<tests> directory.
You may wish to review the F<tests/test.config> configuration file used
for the C<make test> tests.
For example, a simple configuration file (F<swish-e.conf>):
# Example Swish-e Configuration file
# Define *what* to index
# IndexDir can point to a directories and/or a files
# Here it's pointing to the current directory
# Swish-e will also recurse into sub-directories.
IndexDir .
# But only index the .html files
IndexOnly .html
# Show basic info while indexing
IndexReport 1
And that's a simple configuration file.
It says to index all the C<.html> files
in the current directory and sub-directories, if any,
and provide some basic output while indexing.
As mentioned above,
the complete list of all configuration file directives
is detailed in L<SWISH-CONFIG|SWISH-CONFIG>.
=head2 Step 2: Index your Files
Run Swish-e,
using the C<-c> switch to specify the name of the configuration file.
swish-e -c swish-e.conf
Indexing Data Source: "File-System"
Indexing "."
Removing very common words...
no words removed.
Writing main index...
Sorting words ...
Sorting 55 words alphabetically
Writing header ...
Writing index entries ...
Writing word text: Complete
Writing word hash: Complete
Writing word data: Complete
55 unique words indexed.
4 properties sorted.
5 files indexed. 1252 total bytes. 140 total words.
Elapsed time: 00:00:00 CPU time: 00:00:00
Indexing done!
This created the index file C<index.swish-e>.
This is the default index file name,
unless the B<IndexFile> directive is specified in the configuration file:
IndexFile ./website.index
You may use the C<-f> switch to specify a index file at indexing time.
The C<-f> option overrides any C<IndexFile> setting
that may be in the configuration file.
=head2 Step 3: Search
You specify your search terms with the C<-w> switch.
For example, to find the files that contain the word C<sample>,
you would issue the command:
swish-e -w sample
This example assumes that you are in the C<tests> directory.
Swish-e returns the following, in response to this command:
swish-e -w sample
# SWISH format: 2.4.0
# Search words: sample
# Number of hits: 2
# Search time: 0.000 seconds
# Run time: 0.005 seconds
1000 ./test_xml.html "If you are seeing this, the METATAG XML search was successful!" 159
1000 ./test.html "If you are seeing this, the test was successful!" 437
.
So, the word C<sample> was found in two documents.
The first number shown is the relevance (or rank) of the search term,
followed by the file containing the search term,
the title of the document,
and finally, the length of the document (in bytes).
The period ("."), sitting alone at the end,
marks the end of the search results.
Much more information may be retrieved while searching,
by using the C<-x> and C<-H> switches (see L<SWISH-RUN|SWISH-RUN>)
and by using Document Properties (see L<SWISH-CONFIG|SWISH-CONFIG>).
=head2 Phrase Searching
To search for a phrase in a document,
use double-quotes to delimit your search terms.
(The default phrase delimiter is set in C<src/swish.h>.)
You must protect the quotes from the shell.
For example, under Unix:
swish-e -w '"this is a phrase" or (this and that)'
swish-e -w 'meta1=("this is a phrase") or (this and that)'
Or under the Windows C<command.com> shell.
swish-e -w \"this is a phrase\" or (this and that)
The phrase delimiter can be set with the C<-P> switch.
=head2 Boolean Searching
You can use the Boolean operators B<and>, B<or>, or B<not> in searching.
Without these Boolean operatots,
Swish-e will assume you're B<and>ing the words together.
Here are some examples:
swish-e -w 'apples oranges'
swish-e -w 'apples and oranges' ( Same thing )
swish-e -w 'apples or oranges'
swish-e -w 'apples or oranges not juice' -f myIndex
retrieves first the files that contain both the words "apples" and "oranges";
then among those, selects the ones that do not contain the word "juice".
A few other examples to ponder:
swish-e -w 'apples and oranges or pears'
swish-e -w '(apples and oranges) or pears' ( Same thing )
swish-e -w 'apples and (oranges or pears)' ( Not the same thing )
Swish processes the query left to right.
See L<SWISH-SEARCH|SWISH-SEARCH> for more information.
=head2 Context Searching
The C<-t> option in the search command line
allows you to search for words that exist only in specific HTML tags.
This option takes a string of characters as its argument.
Each character represents a different tag in which the word is searched;
that is, you can use any combinations of the following characters:
H search in all <HEAD> tags
B search in the <BODY> tags
t search in <TITLE> tags
h is <H1> to <H6> (header) tags
e is emphasized tags (this may be <B>, <I>, <EM>, or <STRONG>)
c is HTML comment tags (<!-- ... -->)
For example:
# Find only documents with the word "linux" in the <TITLE> tags.
swish-e -w linux -t t
# Find the word "apple" in titles or comments
swish-e -w apple -t tc
=head2 META Tags
As mentioned above,
Metanames are a way to define "fields" in your documents.
You can use the Metanames in your queries to limit the search
to just the words contained in that META name of your document.
For example,
you might have a META-tagged field called C<subjects> in your documents.
This would let you search your documents for the word "foo",
but only return documents where "foo" is within the C<subjects> META tag.
Document I<Properties> are somewhat related:
Properties allow the content of a META tag in a source document
to be stored within the index,
and that text to be returned along with search results.
META tags can have two formats in your documents.
<META NAME="keyName" CONTENT="some Content">
And in XML format
<keyName>
Some Content
</keyName>
If using F<libxml>, you can optionally use a non-HTML tag as a metaname:
<html>
<body>
Hello swish users!
<keyName>
this is meta data
</keyName>.
</body>
This, of course, is invalid HTML.
To continue with our sample C<Swish-e.conf> file,
add the following lines:
# Define META tags
MetaNames meta1 meta2 meta3
Reindex to include the changes:
swish-e -c swish-e.conf
Now search, but this time limit your search to META tag C<meta1>:
swish-e -w 'meta1=metatest1'
Again, please see L<SWISH-RUN|SWISH-RUN> and L<SWISH-CONFIG|SWISH-CONFIG>
for complete documentation of the various indexing and searching options.
=head2 Spidering and Searching with a Web form.
This example demonstrates how to spider a web site
and set up the included CGI script to provide a web-based search page.
This example uses Perl programs that are included in the Swish-e distribution:
F<spider.pl> will be used for reading files from the web server;
F<swish.cgi> will provide the web search form and display results.
As an example,
we will index the Apache Web Server documentation,
installed on the local computer at http://localhost/apache_docs/index.html.
=over 4
=item 1 Make a Working Directory
Create a directory to store the Swish-e configuration and the Swish-e index.
~$ mkdir web_index
~$ cd web_index/
~/web_index$
=item 2 Create a Swish-e Configuration file
~/web_index$ cat swish.conf
# Swish-e config to index the Apache documentation
#
# Use spider.pl for indexing (location of spider.pl set at installation time)
IndexDir spider.pl
# Use spider.pl's default configuration and specify the URL to spider
SwishProgParameters default http://localhost/apache_docs/index.html
# Allow extra searching by title, path
Metanames swishtitle swishdocpath
# Set StoreDescription for each parser
# to display context with search results
StoreDescription TXT* 10000
StoreDescription HTML* <body> 10000
=item 3 Generate the Index
Now, run Swish-e to create the index:
~/web_index$ swish-e -S prog -c swish.conf
Indexing Data Source: "External-Program"
Indexing "spider.pl"
/usr/local/lib/swish-e/spider.pl: Reading parameters from 'default'
Summary for: http://localhost/apache_docs/index.html
Duplicates: 4,188 (349.0/sec)
Off-site links: 276 (23.0/sec)
Skipped: 1 (0.1/sec)
Total Bytes: 2,090,125 (174177.1/sec)
Total Docs: 147 (12.2/sec)
Unique URLs: 149 (12.4/sec)
Removing very common words...
no words removed.
Writing main index...
Sorting words ...
Sorting 7736 words alphabetically
Writing header ...
Writing index entries ...
Writing word text: Complete
Writing word hash: Complete
Writing word data: Complete
7736 unique words indexed.
5 properties sorted.
147 files indexed. 2090125 total bytes. 200783 total words.
Elapsed time: 00:00:13 CPU time: 00:00:02
Indexing done!
The above output is actually a mix of output from both Swish-e
and C<spider.pl>.
C<spider.pl> reports the
"Summary for: http://localhost/apache_docs/index.html".
Also note that Swish-e knows to find C<spider.pl>
at C</usr/local/lib/swish-e/spider.pl>.
The script installation directory (called C<libexecdir>)
is set at configure time.
You can see your setting by running C<swish-e -h>:
~/web_index$ swish-e -h | grep libexecdir
Scripts and Modules at: (libexecdir) = /usr/local/lib/swish-e
This directory will be needed in the next step,
when setting up the CGI script.
Finally, verify that the index can be searched from the command line:
~/web_index$ swish-e -w installing -m3
# SWISH format: 2.4.0
# Search words: installing
# Removed stopwords:
# Number of hits: 17
# Search time: 0.018 seconds
# Run time: 0.050 seconds
1000 http://localhost/apache_docs/install.html "Compiling and Installing Apache" 17960
718 http://localhost/apache_docs/install-tpf.html "Installing Apache on TPF" 25734
680 http://localhost/apache_docs/windows.html "Using Apache with Microsoft Windows" 27165
.
Now, try limiting the search to the title:
~/web_index$ swish-e -w swishtitle=installing -m3
# SWISH format: 2.3.5
# Search words: swishtitle=installing
# Removed stopwords:
# Number of hits: 2
# Search time: 0.018 seconds
# Run time: 0.048 seconds
1000 http://localhost/apache_docs/install-tpf.html "Installing Apache on TPF" 25734
1000 http://localhost/apache_docs/install.html "Compiling and Installing Apache" 17960
.
Note that the above can also be done using the C<-t> option:
~/web_index$ swish-e -w installing -m3 -tH
=item 4 Set up the CGI script
Swish-e does not include a web server.
So, you must use your locally installed web server.
Apache is highly recommended, of course.
Locate your web server's CGI directory.
This may be a C<cgi-bin> directory in your home directory
or a central C<cgi-bin> directory set up by the web server administrator.
Once this is located,
copy the C<swish.cgi> script into the C<cgi-bin> directory.
Where CGI scripts can be located
depends completely on the web server that is being used
and how it has been configured.
See your web server's documentation or your site's administrator
for additional information.
This example will use a site C<cgi-bin> directory,
located at C</usr/lib/cgi-bin>.
Copy the C<swish.cgi> script into the C<cgi-bin> directory.
Again, we will need the location of the C<libexecdir> directory:
~/web_index$ swish-e -h | grep libexecdir
Scripts and Modules at: (libexecdir) = /usr/local/lib/swish-e
~/web_index$ cd /usr/lib/cgi-bin
/usr/lib/cgi-bin$ su
Password:
/usr/lib/cgi-bin# cp /usr/local/lib/swish-e/swish.cgi.
If your operating system supports symbolic links
B<and> your web server allows programs to be symbolic links,
then you may wish to create a link to the C<swish.cgi> program, instead.
/usr/lib/cgi-bin# ln -s /usr/local/lib/swish-e/swish.cgi
We need to tell the C<swish.cgi> script where to look
for the index created in the previous step.
It's also recommended to enter the path to the swish-e binary.
Otherwise, the C<swish.cgi> script will look for the binary in the C<PATH>,
and that may change when running under the CGI environment.
Here's the configuration file:
/usr/lib/cgi-bin# cat .swishcgi.conf
return {
title => 'Search Apache Documentation',
swish_binary => '/usr/local/bin/swish-e',
swish_index => '/home/moseley/web_index/index.swish-e',
}
Now, test the script from the command line (as a normal user!):
/usr/lib/cgi-bin# exit
exit
/usr/lib/cgi-bin$ ./swish.cgi | head
Content-Type: text/html; charset=ISO-8859-1
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>
Search Apache Documentation
</title>
</head>
<body>
Notice that the CGI script returns the HTTP header (Content-Type)
and the body of the web page,
just like a well behaved CGI scrip should do.
Now, test using the web server
(this step depends on the location of your C<cgi-bin> directory).
This example uses the "GET" command that is part of the LWP Perl library,
but any web browser can run this test.
/usr/lib/cgi-bin$ GET http://localhost/cgi-bin/swish.cgi | head
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Tranitional//EN">
<html>
<head>
<title>
Search Apache Documentation
</title>
</head>
<body>
<h2>
The script reports errors to stderr,
so consult the web server's error log if problems occur.
The message "Service currently unavailable",
reported by running C<swish.cgi>,
typically indicates a configuration error;
the exact problem will be listed in the web server's error log.
Detailed instructions on using the C<swish.cgi> script
and debugging tips can be found by running:
$ perldoc swish.cgi
while in the C<cgi-bin> directory where C<swish.cgi> was copied.
The spider program C<spider.pl> also has a large number
of configuration options.
Documentation is also available
in the directory C<$prefix/share/doc/swish-e> or at
http://swish-e.org.
Note: Also check out the C<search.cgi> script,
found at the same location as the C<swish.cgi> script.
This is more of a skeleton script,
for those that want to create a custom search script.
=back
Now you are ready to search.
=head1 Indexing Other Types of Documents - Filtering
Swish-e can only index HTML, XML, and text documents.
In order to index other documents,
such as PDF or MS Word documents,
you must use a utility to convert or "filter" those documents.
How documents are filtered with Swish-e has changed over time.
This has resulting in a bit of confusion.
It's also a somewhat complex process,
as different programs need to communicate with each other.
You may wish to read the Swish-e FAQ question on filtering,
before continuing here.
L<How do I filter documents?|SWISH-FAQ/"How Do I filter documents?">
=head2 Filtering Overview
There are two ways to filter documents with Swish-e.
Both are described in the L<SWISH-CONFIG|SWISH-CONFIG> man page.
They use the C<FileFilter> directive
and the C<SWISH::Filter> Perl module.
The C<FileFilter> directive is a general-purpose method of filtering.
It allows running of an external program for each document processed
(based on file extension),
and requires one or more external programs.
These programs open an input file, convert as needed,
and write their output to standard output.
Previous versions of Swish-e (before 2.4.0)
used a collection of filter programs
for converting files such as PDF or MS Word documents.
The external programs call other program to do the work of filtering
(e.g. F<pdftotext> to extract the contents from PDF files).
Although these filter programs are still included
with the Swish-e distribution as examples,
it is recommended to use the C<SWISH::Filter> method, instead.
One disadvantage of using C<FileFilter>
is that the filter program is run once
for every document that needs to be filtered.
This can slow down the indexing process B<substantially>.
The C<SWISH::Filter> Perl module works very much like the old system
and uses the same helper programs.
Convieniently, however,
it provides a single interface for filtering all types of documents.
The primary advantage of C<SWISH::Filter>
is that it is built into the program used for spidering web sites (spider.pl),
so all that's required is installing the filter programs that do the
actual work of filtering (e.g. F<catdoc>, F<xpdf>).
(The Windows binary includes some of the filter programs.)
But, Swish-e will not use C<SWISH::Filter> by default
when using the file system method of indexing.
To use C<SWISH::Filter> when indexing by file system method (-S fs),
you can use a C<FileFilter> directive with the C<swish_filter.pl> filter
(which is just a program that uses C<SWISH::Filter>)
or use the C<-S prog> method of indexing
and use the C<DirTree.pl> program for fetching documents.
C<DirTree.pl> is included with the Swish-e distribution
and is designed to work with C<SWISH::Filter>.
Using DirTree.pl will likely be a faster way to index,
since the C<SWISH::Filter> set of modules
does not need to be compiled for every document
that needs to be filtered.
See the contents of C<swish_filter.pl> and C<DirTree.pl>
for specifics on their use.
=head2 Filtering Examples
The C<FileFilter> directive can be used in your config file
to convert documents, based on their extensions.
This is the old way of filtering,
but provides an easy way to add filters to Swish-e.
For example:
FileFilter .pdf pdftotext "'%p' -"
IndexContents TXT* .pdf
will cause all C<.pdf> files to be filtered through the F<pdftotext> program
(part of the F<Xpdf> package)
and to parse the resulting output (from F<pdftotext>)
with the text ("TXT") parser.
The other way to filter documents
is to use a C<-S prog> prograam
and convert the documents before passing them onto Swish-e.
For example, C<spider.pl> makes use of the C<SWISH::Filter"> Perl module,
included with the Swish-e distribution.
C<SWISH::Filter> is passed a document and the document's content type;
it looks for modules and utilities to convert the document
into one of the types that Swish-e can index.
Swish-e comes ready to index PDF, MS Word, MP3 ID3 tags,
and MS Excel file types.
But these filters need extra modules or tools to do the actual conversion.
For example, the Swish-e distribution includes a module called
C<SWISH::Filter::Pdf2HTML>
that uses the F<pdftotext> and F<pdfinfo> utilities
provided by the F<Xpdf> package.
This means that if you are using C<spider.pl>
to spider your web site
and you wish to index PDF documents,
all that is needed is to install the Xpdf package
and Swish-e (with the help of spider.pl) will begin indexing your PDF files.
Ok, so what does all that mean?
For a very simple site,
you should be able to run this:
$ /usr/local/lib/swish-e/spider.pl default http://localhost/ | swish-e -S prog -i stdin
which is running the spider with default spider settings,
indexing the Web server on localhost,
and piping its output into Swish-e (using the default indexing settings).
Documents will be filtered automatically,
if you have the required helper applications installed.
Most people will not want to just use the default settings
(for one thing, the spider will take a while
because its default is to delay a few seconds between every request).
So, read the documentation for C<spider.pl>,
to learn how to use a spider config file.
Also read L<SWISH-CONFIG|SWISH-CONFIG>
to learn about what configuration options can be used with Swish-e.
The C<SWISH::Filter> documentation provides more details on filtering
and hints for debugging problems when filtering.
=head1 Document Info
$Id: INSTALL.pod 1978 2007-12-08 01:59:17Z karpet $
.
| uddhab/swish-e | swish-e-2.4.7/pod/INSTALL.pod | Perl | mit | 49,434 |
=pod
=head1 NAME
SSL_state_string, SSL_state_string_long - get textual description of state of an SSL object
=head1 SYNOPSIS
#include <openssl/ssl.h>
const char *SSL_state_string(const SSL *ssl);
const char *SSL_state_string_long(const SSL *ssl);
=head1 DESCRIPTION
SSL_state_string() returns a 6 letter string indicating the current state
of the SSL object B<ssl>.
SSL_state_string_long() returns a string indicating the current state of
the SSL object B<ssl>.
=head1 NOTES
During its use, an SSL objects passes several states. The state is internally
maintained. Querying the state information is not very informative before
or when a connection has been established. It however can be of significant
interest during the handshake.
When using nonblocking sockets, the function call performing the handshake
may return with SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE condition,
so that SSL_state_string[_long]() may be called.
For both blocking or nonblocking sockets, the details state information
can be used within the info_callback function set with the
SSL_set_info_callback() call.
=head1 RETURN VALUES
Detailed description of possible states to be included later.
=head1 SEE ALSO
L<ssl(7)>, L<SSL_CTX_set_info_callback(3)>
=head1 COPYRIGHT
Copyright 2001-2020 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
| kipid/blog | nodejs/openssl-master/doc/man3/SSL_state_string.pod | Perl | mit | 1,592 |
:-if(exists_source(library(logicmoo_utils))).
:- if((multifile(baseKB:ignore_file_mpreds/1),dynamic(baseKB:ignore_file_mpreds/1), (prolog_load_context(file,F) -> ain(baseKB:ignore_file_mpreds(F)) ; true))).
:-endif.
:-if((multifile(baseKB:mpred_is_impl_file/1),dynamic(baseKB:mpred_is_impl_file/1),prolog_load_context(file,F),call(assert_if_new,baseKB:mpred_is_impl_file(F)))).
:-endif.
:- endif.
:- module(eggdrop_next, [
add_maybe_static/2,bot_nick/1,call_in_thread/1,call_with_results/3,check_put_server_count/1,cit/0,close_ioe/3,consultation_codes/3,
consultation_thread/2,ctcp/6,ctrl_nick/1,ctrl_pass/1,ctrl_port/1,ctrl_server/1,deregister_unsafe_preds/0,egg_go/0,
egg_go_fg/0,eggdropConnect/0,eggdropConnect/2,eggdropConnect/4,eggdrop_bind_user_streams/0,escape_quotes/2,flush_all_output/0,
flushed_privmsg/3,
format_nv/2,get2react/1,get_session_prefix/1,ignore_catch/1,ignored_source/1,ircEvent/3,irc_call/4,irc_filtered/4,
irc_receive/5,is_callable_egg/1,is_empty/1,is_lisp_call_functor/1,join/4,list_replace_egg/4,msgm/5,my_wdmsg/1,
part/5,privmsg/2,privmsg_session/2,pubm/5,putnotice/2,read_codes_and_send/2,read_egg_term/3,read_from_agent_and_send/2,
recordlast/3,remove_anons/2,remove_pred_egg/3,say/1,say/2,say/3,say/3,
say/3,sayq/1,show_thread_exit/0,to_egg/1,to_egg/2,unreadable/1,unsafe_preds_egg/3,
update_changed_files_eggdrop/0,vars_as_comma/0,vars_as_list/0,with_error_channel/2,with_error_to_output/1,with_input_channel_user/3,with_io/1,with_no_input/1,
with_output_channel/2,with_rl/1,egg:stdio/3,lmcache:vars_as/1,ignored_channel/1,lmconf:chat_isWith/2,lmconf:chat_isRegistered/3,last_read_from/3,
lmconf:chat_isChannelUserAct/4,
attvar_to_dict_egg/2,
% dict_to_attvar_egg/2,
format_nv/2
% eggdrop_e:stream_close/1,eggdrop_e:stream_read/2,eggdrop_e:stream_write/2,eggdrop_io:stream_close/1,eggdrop_io:stream_read/2,
% eggdrop_io:stream_write/2,t_l:put_server_count/1,t_l:put_server_no_max/0,t_l:session_id/1
]).
:- set_module(class(library)).
:- user:ensure_loaded(library(clpfd)).
:- '@'((
op(1199,fx,('==>')),
op(1190,xfx,('::::')),
op(1180,xfx,('==>')),
op(1170,xfx,'<==>'),
op(1160,xfx,('<-')),
op(1150,xfx,'=>'),
op(1140,xfx,'<='),
op(1130,xfx,'<=>'),
op(600,yfx,'&'),
op(600,yfx,'v'),
op(350,xfx,'xor'),
op(300,fx,'~'),
op(300,fx,'-')),user).
:- if((fail,exists_source(library(atts)))).
:- set_prolog_flag(metaterm,true).
:- use_module(library(atts)).
:- endif.
:- if(exists_source(library(logicmoo_utils))).
:- user:use_module(system:library(logicmoo_utils)).
:- endif.
:- meta_predicate
call_in_thread(0),
call_with_results(+, 0, ?),
call_with_results_0(0, ?),
call_with_results_nondet(0, ?),
call_with_results_nondet_vars(0, ?),
ignore_catch(0),
with_error_channel(+, 0),
with_error_to_output(0),
with_input_channel_user(+, +, 0),
with_io(0),
with_no_input(0),
with_output_channel(+, 0),
with_rl(0).
:- user:use_module(library(logicmoo_util_common)).
same_streams(Alias1,Alias2):- stream_property(S1,alias(Alias1)),stream_property(S2,alias(Alias2)),!,S1==S2.
%% my_wdmsg( ?Msg) is det.
%
% My Wdmsg.
%
my_wdmsg(Msg):- notrace(my_wdmsg0(Msg)).
my_wdmsg0(List):-is_list(List),catch(text_to_string(List,CMD),_,fail),List\==CMD,!,my_wdmsg(CMD).
my_wdmsg0(Msg):- if_defined(real_user_output(S)),!,my_wdmsg(S,Msg).
my_wdmsg0(Msg):- stream_property(_,alias(main_user_error)),!,my_wdmsg(main_user_error,Msg).
my_wdmsg0(Msg):- get_main_error_stream(ERR),!,my_wdmsg(ERR,Msg).
my_wdmsg0(Msg):- debugm(Msg).
my_wdmsg(S,Msg):- string(Msg),format(S,'~N% ~w~N',[Msg]),flush_output_safe(S),!.
my_wdmsg(S,Msg):- format(S,'~N% ~q.~n',[Msg]),flush_output_safe(S),!.
:- dynamic(lmconf:chat_isWith/2).
:- thread_local(t_l:(disable_px)).
:- my_wdmsg("HI there").
egg_to_string(A,S):- notrace(egg_to_string0(A,S)).
egg_to_string0(A,S):- var(A),!,trace_or_throw(var_egg_to_string(A,S)).
egg_to_string0(A,S):- on_x_fail(text_to_string(A,S)),!.
egg_to_string0([A],S):- on_x_fail(atom_string(A,S)),!.
egg_to_string0(A,S):- on_x_fail(atom_string(A,S)),!.
:- dynamic(real_user_output/1).
:- volatile(real_user_output/1).
egg_booting :- source_file_property(reloading, true) ,!.
egg_booting :- thread_self(M), M \== main,!.
egg_booting :- ignore((stream_property(S,alias(user_output)),asserta(real_user_output(S)),set_stream(S,alias(main_user_output)))),
ignore(( stream_property(S,alias(user_error)),asserta(real_user_output(S)),!,set_stream(S,alias(main_user_error)))).
:- during_boot(egg_booting).
% ===================================================================
% IRC CONFIG
% ===================================================================
:- if(exists_file('.ircbot.pl')).
:- include('.ircbot.pl').
:- else.
%% bot_nick( ?PrologMUD1) is det.
%
% Bot Nick.
%
bot_nick("PrologMUD").
%% ctrl_server( ?Localhost1) is det.
%
% Ctrl Server.
%
ctrl_server(localhost).
%% ctrl_nick( ?Swipl1) is det.
%
% Ctrl Nick.
%
ctrl_nick("swipl").
%% ctrl_pass( ?Top5ecret1) is det.
%
% Ctrl Pass.
%
ctrl_pass("top5ecret").
%% ctrl_port( ?Port) is det.
%
% Ctrl Port.
%
ctrl_port(3334).
:- endif.
:- meta_predicate call_with_results_nondet_vars(0,*).
:- meta_predicate call_with_results_nondet(0,*).
:- meta_predicate call_with_results_0(0,*),with_rl(0).
% :- use_module(library(logicmoo/util/logicmoo_util_prolog_streams),[with_output_to_stream_pred/4]).
:- module_transparent(ircEvent/3).
% from https://github.com/logicmoo/PrologMUD/tree/master/src_lib/logicmoo_util
% supplies locally/2,atom_concats/2, dmsg/1, my_wdmsg/1, must/1, if_startup_script/0
:- ensure_loaded(system:library(logicmoo_utils)).
% :- use_module(library(resource_bounds)).
:- ensure_loaded(library(logicmoo_utils)).
/*
TODO
* one may consider letting it wait until a query is completed with a `.'
* consider using numbervars/[3,4] <http://www.swi-prolog.org/pldoc/man?section=manipterm#numbervars/3>,
<http://www.swi-prolog.org/pldoc/man?section=termrw#write_term/2> (option numbervars)
for printing the variables (named ones in query, and freshly generated ones)
* skip printing toplevel vars marked with "_" in findall(_X, fact(_X), Xs).
* perhaps use "commalists" instead of ordinary lists for each solution ? (makes it look more like a traditional interactor reply, and looks more sensible, logically)
*/
%% lmconf:chat_isRegistered( ?Channel, ?Agent, ?Execute3) is det.
%
% If Is A Registered.
%
:- dynamic(lmconf:chat_isRegistered/3).
lmconf:chat_isRegistered(Channel,Agent,kifbot):-lmconf:chat_isWith(Channel,Agent).
lmconf:chat_isRegistered(_,"someluser",execute):-!,fail.
lmconf:chat_isRegistered("#ai",_,execute):-ignore(fail).
lmconf:chat_isRegistered("#pigface",_,execute):-ignore(fail). % havent been there since 2001
lmconf:chat_isRegistered("#logicmoo",_,execute):-ignore(fail).
lmconf:chat_isRegistered("#kif",_,execute):-ignore(fail).
lmconf:chat_isRegistered("#rdfig",_,execute):-ignore(fail).
lmconf:chat_isRegistered("##prolog",_,execute):-!.
% all may execture since th ey are using ?-
lmconf:chat_isRegistered(_,_,execute):-!.
:- export((egg_go/0,ircEvent/3,lmconf:chat_isRegistered/3)).
% ===================================================================
% Deregister unsafe preds
% ===================================================================
:-use_module(library(process)).
%% unsafe_preds_egg( ?M, ?F, ?A) is det.
%
% Unsafe Predicates Egg.
%
unsafe_preds_egg(M,F,A):-M=files_ex,current_predicate(M:F/A),member(X,[delete,copy]),atom_contains(F,X).
%unsafe_preds_egg(M,F,A):-M=process,current_predicate(M:F/A),member(X,[kill,create]),atom_contains(F,X).
unsafe_preds_egg(M,F,A):-M=system,member(F,[shell,halt]),current_predicate(M:F/A).
:- export(remove_pred_egg/3).
%% remove_pred_egg( ?M, ?F, ?A) is det.
%
% Remove Predicate Egg.
%
remove_pred_egg(_,F,A):-member(_:F/A,[_:delete_common_prefix/4]),!.
remove_pred_egg(M,F,A):- functor(P,F,A),
(current_predicate(M:F/A) -> ignore((catch(redefine_system_predicate(M:P),_,true),abolish(M:F,A)));true),
M:asserta((P:-(my_wdmsg(error(call(P))),throw(permission_error(M:F/A))))).
% :-use_module(library(uid)).
% only if root
%% deregister_unsafe_preds is det.
%
% Deregister Unsafe Predicates.
%
deregister_unsafe_preds:-!.
deregister_unsafe_preds:- current_predicate(system:kill_unsafe_preds/0),!.
deregister_unsafe_preds:- if_defined(getuid(0),true),forall(unsafe_preds_egg(M,F,A),remove_pred_egg(M,F,A)).
deregister_unsafe_preds:-!.
% [Optionaly] Solve the Halting problem
:-redefine_system_predicate(system:halt).
:-abolish(system:halt,0).
%% halt is det.
%
% Hook To [system:halt/0] For Module Eggdrop.
% Halt.
%
system:halt:- format('the halting problem is now solved!').
% :- deregister_unsafe_preds.
% ===================================================================
% Eggrop interaction
% ===================================================================
:- use_module(library(socket)).
:- volatile(egg:stdio/3).
:- dynamic(egg:stdio/3).
:- ain(mtExact(lmcache)).
:- ain(mtExact(lmconf)).
%% eggdropConnect is det.
%
% Eggdrop Connect.
%
eggdropConnect:- eggdropConnect(_Host,_Port,_CtrlNick,_Pass).
%% eggdropConnect( ?CtrlNick, ?Port) is det.
%
% Eggdrop Connect.
%
eggdropConnect(CtrlNick,Port):-eggdropConnect(_Host,Port,CtrlNick,_Pass).
%% eggdropConnect( ?Host, ?Port, ?CtrlNick, ?Pass) is det.
%
% Eggdrop Connect.
%
eggdropConnect(Host,Port,CtrlNick,Pass):-
ignore(ctrl_server(Host)),
ignore(ctrl_port(Port)),
ignore(ctrl_nick(CtrlNick)),
ignore(ctrl_pass(Pass)),
tcp_socket(SocketId),
my_wdmsg(tcp_connect(SocketId,Host:Port)),
tcp_connect(SocketId,Host:Port),
tcp_open_socket(SocketId, IN, OutStream),
set_stream(IN,type(binary)),
set_stream(OutStream,type(binary)),
format(OutStream,'~w\n',[CtrlNick]),flush_output_safe(OutStream),
format(OutStream,'~w\n',[Pass]),flush_output_safe(OutStream),
% format(OutStream,'~w\n',[CtrlNick]),flush_output(OutStream),
% format(OutStream,'~w\n',[Pass]),flush_output(OutStream),
retractall(egg:stdio(CtrlNick,_,_)),
asserta((egg:stdio(CtrlNick,IN,OutStream))),!.
:-export(consultation_thread/2).
%% consultation_thread( ?CtrlNick, ?Port) is det.
%
% Consultation Thread.
%
consultation_thread(CtrlNick,Port):-
eggdropConnect(CtrlNick,Port),
to_egg('.echo off\n'),
to_egg('.console ~w ""\n',[CtrlNick]),
must(bot_nick(PrologMUDNick)),
to_egg('.set nick ~w\n',[PrologMUDNick]),
must(egg:stdio(CtrlNick,IN,_)),!,
% loop
to_egg('.console #logicmoo\n',[]),
% say(dmiles,consultation_thread(CtrlNick,Port)),
% say("#logicmoo","hi therre!"),
repeat,
nop(notrace(update_changed_files_eggdrop)),
notrace(catch(read_line_to_codes(IN,Text),_,Text=end_of_file)),
once(consultation_codes(CtrlNick,Port,Text)),
Text==end_of_file,!.
%% is_callable_egg( ?CMD) is det.
%
% If Is A Callable Egg.
%
is_callable_egg(CMD):-var(CMD),!,fail.
is_callable_egg((A,B)):-!,is_callable_egg(A),is_callable_egg(B).
is_callable_egg((A;B)):-!,is_callable_egg(A),is_callable_egg(B).
is_callable_egg(CMD):- callable(CMD),
functor(CMD,F,A),
current_predicate(F/A),!.
%:-meta_predicate(module_call(+,0)).
%module_call(M,CMD):- CALL=M:call(CMD), '@'(catch(CALL,E,(my_wdmsg(E:CALL),throw(E))),M).
%:-meta_predicate(user_call(0)).
%user_call(M:CMD):-!,show_call(module_call(M,CMD)).
%user_call(CMD):-module_call('user',CMD).
%% consultation_codes( ?CtrlNick, ?Port, ?Codes) is det.
%
% Consultation Codes.
%
consultation_codes(CtrlNick,Port,end_of_file):-!,consultation_thread(CtrlNick,Port).
consultation_codes(_BotNick,_Port,Text):-
notrace((text_to_string(Text,String),
catch(read_term_from_atom(String,CMD,[]),_E,(my_wdmsg(String),!,fail)),!,
is_callable_egg(CMD),
my_wdmsg(maybe_call(CMD)))),!,
catchv(CMD,E,my_wdmsg(E:CMD)).
% IRC EVENTS Bubble from here
:- export(get2react/1).
%% get2react( ?ARG1) is det.
%
% Get2react.
%
get2react([L|IST1]):- CALL =.. [L|IST1],functor(CALL,F,A),
show_failure((current_predicate(F/A))),show_failure((CALL)).
:- thread_local(t_l: session_id/1).
% ===================================================================
% IRC interaction
% ===================================================================
:- thread_local t_l:default_channel/1, t_l:default_user/1, t_l:current_irc_receive/5.
% IRC EVENTS FROM CALL
chon(W,N):- nop(chon(_,W,N)).
%% part( ?USER, ?HOSTMASK, ?TYPE, ?DEST, ?MESSAGE) is det.
%
% Part.
%
part(USER, HOSTMASK,TYPE,DEST,MESSAGE):- irc_receive(USER, HOSTMASK,TYPE,DEST,part(USER, HOSTMASK,TYPE,DEST,MESSAGE)).
%% join( ?USER, ?HOSTMASK, ?TYPE, ?DEST) is det.
%
% Join.
%
join(USER, HOSTMASK,TYPE,DEST):- irc_receive(USER, HOSTMASK,TYPE,DEST,join(USER, HOSTMASK,TYPE,DEST)).
%% msgm( ?USER, ?HOSTMASK, ?TYPE, ?DEST, ?MESSAGE) is det.
%
% Msgm.
%
msgm(USER, HOSTMASK,TYPE,DEST,MESSAGE):- irc_receive(USER, HOSTMASK,TYPE,DEST,say(MESSAGE)).
%% ctcp( ?USER, ?HOSTMASK, ?FROM, ?DEST, ?TYPE, ?MESSAGE) is det.
%
% Ctcp.
%
ctcp(USER, HOSTMASK,_FROM,DEST,TYPE,MESSAGE):- irc_receive(USER, HOSTMASK,TYPE,DEST,ctcp(TYPE,MESSAGE)).
%% pubm( ?USER, ?HOSTMASK, ?TYPE, ?DEST, ?MESSAGE) is det.
%
% Pubm.
%
pubm(USER, HOSTMASK,TYPE,DEST,MESSAGE):- irc_receive(USER, HOSTMASK,TYPE,DEST,say(MESSAGE)).
%% irc_receive( ?USER, ?HOSTMASK, ?TYPE, ?DEST, ?MESSAGE) is det.
%
% Irc Receive.
%
irc_receive(USER,HOSTMASK,TYPE,DEST,MESSAGE):-
my_wdmsg(irc_receive(USER,HOSTMASK,TYPE,DEST,MESSAGE)),!,
agent_module(USER,ID),
call_in_thread(
with_engine(ID,
% with_error_to_output
(
locally([
t_l:put_server_count(0),
t_l:default_channel(DEST),
t_l:default_user(USER),
t_l:session_id(ID),
t_l:current_irc_receive(USER, HOSTMASK,TYPE,DEST,MESSAGE)],
((eggdrop_bind_user_streams,
must(t_l:default_channel(DEST)),
ircEvent(DEST,USER,MESSAGE))))))).
be_engine:- repeat,engine_fetch(Term),once(Term),engine_yield(Term),fail.
with_engine(_,Goal):- !, Goal.
with_engine(E,Goal):- current_engine(EE),EE==E,!,engine_post(E,Goal),get_answers(E, R),my_wdmsg(r(E=R)).
with_engine(E,Goal):- catch(engine_create(success,Goal,E),_,(engine_destroy(E),engine_create(success,be_engine,E))),
get_answers(E,R),my_wdmsg(r(E=R)).
get_answers(E, [H|T]) :-
engine_next(E, H), !,
get_answers(E, T).
get_answers(_, []).
%% with_rl( :Call) is det.
%
% Using Resource Limit.
%
% :- use_module(library(resource_bounds)).
%with_rl(Call):- thread_self(main),!,rtrace((guitracer,trace,Call)).
with_rl(Call):- thread_self(main),!,Call.
with_rl(Call):- !,nodebugx(Call).
% with_rl(Goal):- show_call(eggdrop,nodebugx(resource_bounded_call(Goal, 1000.0, _Status, []))).
with_rl(Call):- nodebugx(call_with_time_limit(30,Call)).
% ===================================================================
% IRC EVENTS
% ===================================================================
:- dynamic(last_read_from/3).
% convert all to strings
%% ignored_source( ?From) is det.
%
% Ignored Source.
%
ignored_source(From):-var(From),!,fail.
ignored_source("yesbot").
ignored_source(From):-not(string(From)),!,text_to_string(From,String),!,ignored_source(String).
% from bot telnet
ignored_source(From):- atom(From),atom_length(From,1).
% from the process or bot
ignored_source(From):-
bot_nick(BotNick),ctrl_nick(CtrlNick),arg(_,vv(BotNick,CtrlNick),Ignore),atom_contains(From,Ignore),!.
:-dynamic(lmconf:chat_isChannelUserAct/4).
:-dynamic(ignored_channel/1).
:-dynamic(user:irc_event_hooks/3).
:-multifile(user:irc_event_hooks/3).
%% user:irc_event_hooks( ?Channel, ?User, ?Stuff) is det.
%
% Hook To [user:irc_event_hooks/3] For Module Eggdrop.
% Irc Event Hooks.
%
user:irc_event_hooks(_Channel,_User,_Stuff):-fail.
%% recordlast( ?Channel, ?User, ?What) is det.
%
% Recordlast.
%
recordlast(Channel,User,say(What)):-!,retractall(lmconf:chat_isChannelUserAct(Channel,User,say,_)),asserta(lmconf:chat_isChannelUserAct(Channel,User,say,What)),!.
recordlast(Channel,User,What):-functor(What,F,_),retractall(lmconf:chat_isChannelUserAct(Channel,User,F,_)),asserta(lmconf:chat_isChannelUserAct(Channel,User,F,What)),!.
% awaiting some inputs
%% ircEvent( ?DEST, ?User, ?Event) is det.
%
% Irc Event.
%
ircEvent(DEST,User,say(W)):-
term_to_atom(cu(DEST,User),QUEUE),
message_queue_property(_, alias(QUEUE)),
show_call(ircEvent,thread_send_message(QUEUE,W)).
% ignore some inputs
ircEvent(Channel,Agent,_):- (ignored_channel(Channel) ; ignored_source(Agent)) ,!.
% attention (notice the fail to disable)
ircEvent(Channel,Agent,say(W)):- fail,
atom_contains(W,"goodbye"),!,retractall(lmconf:chat_isWith(Channel,Agent)).
ircEvent(Channel,Agent,say(W)):- fail,
(bot_nick(BotNick),atom_contains(W,BotNick)),
retractall(lmconf:chat_isWith(Channel,Agent)),!,
asserta(lmconf:chat_isWith(Channel,Agent)),!,
say(Channel,[hi,Agent,'I will answer you in',Channel,'until you say "goodbye"']).
ircEvent(Channel,Agent,Event):- once(doall(call_no_cuts(user:irc_event_hooks(Channel,Agent,Event)))),fail.
% Say -> Call
ircEvent(Channel,Agent,say(W)):-
% with_dmsg_to_main
((
forall(
(read_egg_term(W,CMD,Vs),CMD\==end_of_file),
% eggdrop:read_each_term_egg(W,CMD,Vs),
ircEvent(Channel,Agent,call(CMD,Vs))))),!.
% Call -> call_with_results
ircEvent(Channel,Agent,call(CALL,Vs)):-
with_dmsg_to_main((
thread_self(Self), tnodebug(Self),
use_agent_module(Agent),
dmsg(irc_filtered(Channel,Agent,CALL,Vs)),
once(((irc_filtered(Channel,Agent,CALL,Vs)) -> true ; dmsg(failed_irc_filtered(Channel,Agent,CALL,Vs)))),
save_agent_module(Agent))),!.
ircEvent(Channel,User,Method):-recordlast(Channel,User,Method), my_wdmsg(unused(ircEvent(Channel,User,Method))).
:- dynamic(lmconf:chat_isModule/3).
:- module_transparent(use_agent_module/1).
:- module_transparent(save_agent_module/1).
:- if(true).
use_agent_module(AgentS):- any_to_atom(AgentS,Agent),source_and_module_for_agent(Agent,Module,CallModule),!,'$set_source_module'(Module),'$set_typein_module'(CallModule).
save_agent_module(AgentS):- any_to_atom(AgentS,Agent), retractall(lmconf:chat_isModule(Agent,_)), '$set_source_module'(Next,Next),'$module'(CallModule,CallModule),asserta(lmconf:chat_isModule(Agent,Next,CallModule)).
source_and_module_for_agent(Agent,Module,CallModule):- lmconf:chat_isModule(Agent,Module,CallModule),!.
source_and_module_for_agent(Agent,Agent,user):- maybe_add_import_module(Agent,user,end), maybe_add_import_module(Agent,eggdrop,end).
:- else.
use_agent_module(AgentS):- agent_module(AgentS,Agent),
source_and_module_for_agent(Agent,SM,CM),!,
'$set_source_module'(_,SM),'$module'(_,CM),!.
save_agent_module(AgentS):- agent_module(AgentS,Agent),
retractall(lmconf:chat_isModule(Agent,_,_)),
'$current_source_module'(SM),'$current_typein_module'(CM),asserta(lmconf:chat_isModule(Agent,SM,CM)).
source_and_module_for_agent(Agent,SM,CM):- lmconf:chat_isModule(Agent,SM,CM),!.
source_and_module_for_agent(Agent,SM,CM):- \+ atom(Agent),agent_module(Agent,AgentM),Agent\==AgentM,!,source_and_module_for_agent(AgentM,SM,CM).
source_and_module_for_agent(Agent,Agent,Agent):- maybe_add_import_module(Agent,user,end), maybe_add_import_module(Agent,eggdrop,end).
:- endif.
:-export(unreadable/1).
%% unreadable( ?UR) is det.
%
% Unreadable.
%
unreadable(UR):-my_wdmsg(unreadable(UR)).
:-export(eggdrop_bind_user_streams/0).
%% eggdrop_bind_user_streams is det.
%
% Eggdrop Bind User Streams.
%
% eggdrop_bind_user_streams :- !.
eggdrop_bind_user_streams :- thread_self(main),!.
eggdrop_bind_user_streams :-
user:((
user:open_prolog_stream(eggdrop_io, write, Out, []),
user:open_prolog_stream(eggdrop_e, write, Err, []),
set_stream(Out, buffer(line)),
set_stream(Err, buffer(line)),
open_prolog_stream(eggdrop_io, read, In, []),
set_input(In),
set_output(Out),
/* set_stream(In, alias(user_input)),
set_stream(Out, alias(user_output)),
set_stream(Err, alias(user_error)),
set_stream(In, alias(current_input)),
set_stream(Out, alias(current_output)),
set_stream(Err, alias(current_error)),
*/
thread_at_exit(eggdrop:close_ioe(In, Out, Err)))).
:- use_module(library(pengines)).
:- meta_predicate with_error_channel(+,0).
:- meta_predicate ignore_catch(0).
:- meta_predicate call_in_thread(0).
:- meta_predicate with_no_input(0).
:- meta_predicate with_output_channel(+,0).
:- meta_predicate with_input_channel_user(+,+,0).
%% stream_write( ?Stream, ?Out) is det.
%
% Hook To [eggdrop_e:stream_write/2] For Module Eggdrop.
% Stream Write.
%
eggdrop_io:stream_write(_Stream, Out) :- t_l:default_channel(RETURN),say(RETURN,Out).
%% stream_read( ?Stream, ?Data) is det.
%
% Hook To [eggdrop_e:stream_read/2] For Module Eggdrop.
% Stream Read.
%
eggdrop_io:stream_read(_Stream, "") :- !.
eggdrop_io:stream_read(_Stream, Data) :- prompt(Prompt, Prompt), pengines:pengine_input(_{type:console, prompt:Prompt}, Data).
%% stream_close( ?Stream) is det.
%
% Hook To [eggdrop_e:stream_close/1] For Module Eggdrop.
% Stream Close.
%
eggdrop_io:stream_close(_Stream).
eggdrop_e:stream_write(_Stream, Out) :- t_l:default_channel(RETURN),say(RETURN,Out).
eggdrop_e:stream_read(_Stream, "") :- !.
eggdrop_e:stream_read(_Stream, Data) :- prompt(Prompt, Prompt), pengines:pengine_input(_{type:console, prompt:Prompt}, Data).
eggdrop_e:stream_close(_Stream).
%% close_ioe( ?In, ?Out, ?Err) is det.
%
% Close Ioe.
%
close_ioe(In, Out, Err) :-
close(In, [force(true)]),
close(Err, [force(true)]),
close(Out, [force(true)]).
:-export(add_maybe_static/2).
%% add_maybe_static( ?H, ?Vs) is det.
%
% Add Maybe Static.
%
add_maybe_static( H,Vs):- H \= (_:-_), !,add_maybe_static((H:-true),Vs).
add_maybe_static((H:-B),_Vs):- predicate_property(H,dynamic),!,assertz(((H:-B))).
add_maybe_static((H:-B),_Vs):- must_det_l((convert_to_dynamic(H),assertz(((H:-B))),functor(H,F,A),compile_predicates([F/A]))).
% ===================================================================
% IRC CALL/1
% ===================================================================
:-module_transparent(irc_filtered/4).
:-export(irc_filtered/4).
%% irc_filtered( ?Channel, ?Agent, ?CALL, ?Vs) is det.
%
% Irc Event Call Filtered.
%
irc_filtered(_Channel,_Agent,CALL,_Vs):-var(CALL),!.
irc_filtered(_Channel,_Agent,end_of_file,_Vs):-!.
irc_filtered(Channel,Agent,(H :- B ),Vs):- irc_call(Channel,Agent,add_maybe_static((H :- B),Vs),[]),!.
irc_filtered(Channel,Agent,((=>(H)) :- B ),Vs):- ((=>(H :- B)) \== ((=>(H)) :- B )),!,irc_filtered(Channel,Agent,(=>(H :- B)),Vs).
irc_filtered(Channel,Agent,'?-'(CALL),Vs):- nonvar(CALL),!,irc_call(Channel,Agent,CALL,Vs),!.
irc_filtered(Channel,Agent,'==>'(CALL),Vs):- nonvar(CALL),!,irc_call(Channel,Agent,ain(==>(CALL)),Vs),!.
irc_filtered(Channel,Agent,'=>'(CALL),Vs):- nonvar(CALL),!,irc_call(Channel,Agent,ain(CALL),Vs),!.
irc_filtered(Channel,Agent,lispy([S|TERM]),Vs):- is_list([S|TERM]),is_lisp_call_functor(S),!,
(current_predicate(lisp_call/3), irc_call(Channel,Agent, lisp_call([S|TERM],Vs,R),['Result'=R|Vs]));
my_wdmsg(cant_ircEvent_call_filtered(Channel,Agent,[S|TERM],Vs)).
irc_filtered(Channel,Agent,(CALL),Vs):- compound(CALL),!,irc_call(Channel,Agent,ain(CALL),Vs),!.
irc_filtered(Channel,Agent,CALL,Vs):- lmconf:chat_isRegistered(Channel,Agent,executeAll),!,irc_call(Channel,Agent,CALL,Vs),!.
irc_filtered(Channel,Agent,CALL,Vs):- my_wdmsg(unused_ircEvent_call_filtered(Channel,Agent,CALL,Vs)),!.
%% is_lisp_call_functor( ?FUNCTOR) is det.
%
% If Is A Lisp Call Functor.
%
is_lisp_call_functor('?-').
is_lisp_call_functor('?>').
:-module_transparent(irc_call/4).
:-export(irc_call/4).
agent_module(Agent,AgentModule):-
must(nonvar(Agent)),
any_to_atom(Agent,AgentModule),
must(atom(AgentModule)),
(import_module(AgentModule,eggdrop) -> true ;
((add_import_module(AgentModule,baseKB,end),
add_import_module(AgentModule,pfc,end),
add_import_module(AgentModule,eggdrop,end),
add_import_module(AgentModule,lmconf,end),
add_import_module(AgentModule,clpfd,end),
add_import_module(AgentModule,user,end)))).
% tty_control,false
irc_expand_call(_AgentModule,Goal,Bindings,Goal,Bindings):-!.
irc_expand_call(AgentModule,Query,Bindings,Goal,ExpandedBindings):-
must(( '$toplevel':call_expand_query(Query, ExpandedQuery,
Bindings, ExpandedBindings)
-> AgentModule:expand_goal(ExpandedQuery, Goal))).
%% irc_call( ?Channel, ?Agent, ?CALL, ?Vs) is det.
%
% Irc Event Call.
%
% irc_call(Channel,Agent,Query,Bindings):- thread_self(main) -> with_error_to_output(irc_call(Channel,Agent,Query,Bindings)).
irc_call(Channel,Agent,Query,Bindings):-
must(agent_module(Agent,AgentModule)),
irc_expand_call(AgentModule,Query,Bindings,Goal,ExpandedBindings),
(with_error_to_output(( % When plain main
% show_alias_streams,
with_output_channel(Channel,
with_error_channel(Channel,
(
(( % show_alias_streams,
my_wdmsg(do_irc_call(Channel,Agent,AgentModule:Goal,ExpandedBindings)),
% srtrace,
(call_with_results(AgentModule,Goal,ExpandedBindings)))))))))),!.
irc_call(Channel,Agent,CALL,Vs):- once(my_wdmsg(failed_do_irc_call(Channel,Agent,CALL,Vs))),!.
% show_alias_streams:- \+ current_prolog_flag(runtime_debug,3),!.
show_alias_streams:- doall((member(Alias,[user_error,main_user_error,user_error,user_output,
main_user_output,current_output]),
on_x_fail((stream_property(Stream,alias(Alias)),debugm(Alias==Stream))))).
%% cit is det.
%
% Cit.
%
cit:- get_time(HH), call_in_thread(with_error_channel(dmiles:err,writeln(user_error,HH))).
%% cit2 is det.
%
% Cit Extended Helper.
%
cit2:- get_time(HH), rtrace(with_error_channel(dmiles:err,writeln(user_error,HH))).
%% cit3 is det.
%
% Cit3.
%
cit3:- get_time(HH), writeln(user_error,HH).
%% call_in_thread( :Call) is det.
%
% Call In Thread.
%
call_in_thread(CMD):- thread_self(main),!,CMD.
% call_in_thread(CMD):- !,CMD.
% call_in_thread(CMD):- thread_self(Self),thread_property(Self,alias(Alias)),Alias==egg_go,!,CMD.
call_in_thread(CMD):- thread_create(CMD,_,[detached(true)]),!.
call_in_thread(CMD):- thread_self(Self),thread_create(CMD,_,[detached(true),inherit_from(Self)]).
:- dynamic(lmcache:vars_as/1).
% :- thread_local lmcache:vars_as/1.
%% vars_as( ?VarType) is det.
%
% Hook To [lmcache:vars_as/1] For Module Eggdrop.
% Variables Converted To.
%
lmcache:vars_as(comma).
:-export(flush_all_output/0).
%% flush_all_output is det.
%
% Flush All Output.
%
flush_all_output:- on_x_fail((flush_output_safe,flush_output_safe(user_error),flush_output_safe(current_error))),!.
flush_all_output:- flush_output(user_error),flush_output.
:-export(vars_as_list/0).
%% vars_as_list is det.
%
% Variables Converted To List.
%
vars_as_list :- retractall(lmcache:vars_as(_)),asserta(lmcache:vars_as(list)).
:-export(vars_as_comma/0).
%% vars_as_comma is det.
%
% Variables Converted To Comma.
%
vars_as_comma :- retractall(lmcache:vars_as(_)),asserta(lmcache:vars_as(comma)).
attvar_to_dict_egg(AttVar,Dict):-
get_attrs(AttVar,Att3s),
attrs_to_pairs(Att3s,DictPairs),
dict_create(Dict,AttVar,DictPairs).
attrs_to_pairs(att(N,V,Att3s),[N=V|DictPairs]):-!,attrs_to_pairs(Att3s,DictPairs).
attrs_to_pairs(DictPairs,DictPairs).
/*
dict_to_attvar_egg(MOD,Dict):- dict_to_attvar_egg(MOD,Dict,_),!.
dict_to_attvar_egg(MOD,_:Dict,Out):- \+ compound(Dict),!,Out=Dict.
dict_to_attvar_egg(MOD,Mod:Dict,Out):-
is_dict(Dict),dict_pairs(Dict,M,Pairs),
(atom(M)->atts_put(+,Out,M,Pairs);
(var(M)-> (M=Out,put_atts(Out,Mod:Pairs)))),!.
dict_to_attvar_egg(MOD,Mod:Dict,Out):-
compound_name_arguments(Dict,F,Args),
maplist(dict_to_attvar_egg(MOD),Args,ArgsO),!,
compound_name_arguments(Out,F,ArgsO).
*/
%% format_nv( ?N, ?V) is det.
%
% Format Nv.
%
format_nv(N,V):- format('~w=',[N]),write_v(V).
write_v(V):- attvar(V),if_defined(attvar_to_dict_egg(V,Dict)),writeq(Dict),!.
write_v(V):- var(V),(var_property(V,name(EN))->write(EN);writeq(V)),!.
write_v(V):- writeq(V).
:-export(write_varvalues2/1).
%% write_varvalues2( ?Vs) is det.
%
% Write Varvalues Extended Helper.
%
% write_varvalues2(Vs):-lmcache:vars_as(comma),!,write_varcommas2(Vs),write_residuals(Vs).
write_varvalues2([]):-!,flush_all_output.
write_varvalues2(Vs):-
flush_all_output,
write('% '),
copy_term(Vs,Vs,Goals),
write_varvalues3(Vs),
write_goals(Goals),!,
flush_all_output.
writeqln(G):-writeq(G),write(' ').
write_goals([]):-!.
write_goals(List):-write_goals0(List),!,write(' ').
write_goals0([G|Rest]):-write(' '),writeq(G),write_goals(Rest).
write_goals0([]).
%% write_varvalues3( ?ARG1) is det.
%
% Write Varvalues3.
%
write_varvalues3([N=V]):- format_nv(N,V),!.
write_varvalues3([N=V|Vs]):-format_nv(N,V),write(', '),write_varvalues3(Vs),!.
%% write_varcommas2( ?Vs) is det.
%
% Write Varcommas Extended Helper.
%
write_varcommas2(Vs):- copy_term(Vs,CVs),numbervars(CVs,6667,_,[singletons(true),attvar(skip)]),write_varcommas3(CVs).
%% write_varcommas3( ?ARG1) is det.
%
% Write Varcommas3.
%
write_varcommas3([N=V]):-format_nv(N,V),!.
write_varcommas3([N=V|Vs]):-format_nv(N,V), write(','),!,write_varcommas3(Vs),!.
:-export(remove_anons/2).
%% remove_anons( ?ARG1, ?VsRA) is det.
%
% Remove Anons.
%
remove_anons([],[]).
remove_anons([N=_|Vs],VsRA):-atom_concat('_',_,N),!,remove_anons(Vs,VsRA).
remove_anons([N=V|Vs],[N=V|VsRA]):-remove_anons(Vs,VsRA).
un_user1(user:P,P):-!.
un_user1(system:P,P):-!.
un_user1(eggdrop:CMDI,CMDI):-!.
un_user1(P,P).
%% call_with_results(Module, ?CMDI, ?Vs) is det.
%
% Call Using Results.
%
:-module_transparent(call_with_results/3).
:-export(call_with_results/3).
call_with_results(Module,CMDI0,Vs):- remove_anons(Vs,VsRA),!,
un_user1(CMDI0,CMDI),
b_setval('$term', :- CMDI), /* DRM: added for expansion hooks*/
locally(t_l:disable_px,user:expand_goal(CMDI,CMD)),
(CMD==CMDI->true;my_wdmsg(call_with_results(Module,CMDI->CMD))),
show_call(call_with_results_0(Module:CMD,VsRA)),!.
%% call_with_results_0( :Call, ?Vs) is det.
%
% call Using results Primary Helper.
%
:-module_transparent(call_with_results_0/2).
:-export(call_with_results_0/2).
call_with_results_0(CMD,Vs):-
set_varname_list( Vs),
b_setval('$goal_term', CMD), /* DRM: added for expansion hooks*/
flag(num_sols,_,0),
(call_with_results_nondet(CMD,Vs) *->
(deterministic(X),flag(num_sols,N,0),(N\==0->YN='Yes';YN='No'), write(' '),(X=true->write(det(YN,N));write(nondet(YN,N)))) ;
(deterministic(X),flag(num_sols,N,0),(N\==0->YN='Yes';YN='No'),write(' '),(X=true->write(det(YN,N));write(nondet(YN,N))))).
%% call_with_results_nondet( :CMDIN, ?Vs) is nondet.
%
% call Using results Extended Helper.
%
:-module_transparent(call_with_results_nondet/2).
:-export(call_with_results_nondet/2).
call_with_results_nondet(CMDIN,Vs):-
CMDIN = CMD,functor_h(CMD,F,A),A2 is A+1,CMD=..[F|ARGS],atom_concat(F,'_with_vars',FF),
(current_predicate(FF/A2)-> (CMDWV=..[FF|ARGS],append_term(CMDWV,Vs,CCMD)); CCMD=CMD),!,
call_with_results_nondet_vars(CCMD,Vs).
call_with_results_nondet(CCMD,Vs):- call_with_results_nondet_vars(CCMD,Vs).
%% call_with_results_nondet_vars( :CCMD, ?Vs) is nondet.
%
% Call Using Results Helper Number 3..
%
:-module_transparent(call_with_results_nondet_vars/2).
:-export(call_with_results_nondet_vars/2).
call_with_results_nondet_vars(CCMD,Vs):-
user:show_call(eggdrop,(CCMD,flush_output_safe)), flag(num_sols,N,N+1), deterministic(Done),
(once((Done==true -> (once(\+ \+ write_varvalues2(Vs)),write('% ')) ; (once(\+ \+ write_varvalues2(Vs)),N>28)))).
%% with_output_channel( +Channel, :Call) is det.
%
% Using Output Channel.
%
:-export(with_output_channel/2).
:-module_transparent(with_output_channel(+,0)).
% with_output_channel(Channel,CMD):- CMD.
with_output_channel(Channel,CMD):-
with_output_to_predicate(say(Channel),CMD).
%% with_error_channel( +Agent, :Call) is det.
%
% Using Error Channel.
%
:- export(with_error_channel/2).
:- module_transparent(with_error_channel/2).
/* *
with_error_channel(_Agent, CMD):- !, CMD.
with_error_channel(Agent,CMD):- fail,
current_input(IN),current_output(OUT),
get_main_error_stream(MAINERROR),
set_prolog_IO(IN,OUT,MAINERROR),
new_memory_file(MF),
open_memory_file(MF, write, ERR),
set_prolog_IO(IN,OUT,ERR),!,
setup_call_cleanup_each(CMD,(ignore_catch(flush_output(ERR)),ignore_catch(close(ERR)),read_from_agent_and_send(Agent,MF))).
* */
with_error_channel(Agent, CMD):- !, with_error_to_predicate(say(Agent),CMD).
with_error_channel(_Agent, CMD):- !, CMD.
with_error_channel(_Agent,CMD):- !, with_error_to_output(CMD).
%% with_input_channel_user( +Channel, +User, :Call) is det.
%
% Using Input Channel User.
%
with_input_channel_user(_,_,CMD):- !, with_no_input(CMD).
with_input_channel_user(Channel,User,CMD):-
with_input_from_predicate(last_read_from(Channel,User),CMD).
:-export(with_io/1).
:-meta_predicate(with_io(0)).
%% with_io( :Call) is det.
%
% Using Input/output.
%
with_io(CMD):-!,CMD.
with_io(CMD):-
with_dmsg_to_main((
current_input(IN),current_output(OUT),get_thread_current_error(Err),
call_cleanup(set_prolog_IO(IN,OUT,Err),CMD,(set_input(IN),set_output(OUT),set_error_stream(Err))))).
%% with_no_input( :Call) is det.
%
% Using No Input.
%
% with_no_input(CMD):- CMD.
with_no_input(CMD):- current_input(Prev), open_chars_stream([e,n,d,'_',o,f,'_',f,i,l,e,'.'],In),set_input(In),!,call_cleanup(CMD,set_input(Prev)).
with_no_input(CMD):- open_chars_stream([e,n,d,'_',o,f,'_',f,i,l,e,'.'],In),current_output(OUT), set_prolog_IO(In,OUT,user_error ),CMD.
%% ignore_catch( :CALL) is det.
%
% Ignore Catch.
%
ignore_catch(CALL):-ignore(catch(CALL,E,my_wdmsg(ignore_catch(E:CALL)))).
:- meta_predicate with_error_to_output(0).
%% with_error_to_output( :Call) is det.
%
% Using Error Converted To Output.
%
with_error_to_output(CMD):-
current_input(IN),current_output(OUT),!,
with_io((set_prolog_IO(IN,OUT,OUT), CMD)).
%% read_from_agent_and_send( ?Agent, ?MF) is det.
%
% Read Converted From Agent And Send.
%
read_from_agent_and_send(Agent,MF):- open_memory_file(MF, read, Stream,[ free_on_close(true)]),ignore_catch(read_codes_and_send(Stream,Agent)),ignore_catch(close(Stream)).
%% read_codes_and_send( ?IN, ?Agent) is det.
%
% Read Text And Send.
%
read_codes_and_send(IN,Agent):- at_end_of_stream(IN),!,my_wdmsg(say(Agent,done)).
read_codes_and_send(IN,Agent):- repeat,read_line_to_string(IN,Text),say(Agent,Text),at_end_of_stream(IN),!.
%:-servantProcessCreate(killable,'Consultation Mode Test (KIFBOT!) OPN Server',consultation_thread(swipl,3334),Id,[]).
%% update_changed_files_eggdrop is det.
%
% Update Changed Files Eggdrop.
%
% update_changed_files_eggdrop :- !.
update_changed_files_eggdrop :-
with_dmsg_to_main(( with_no_dmsg((
set_prolog_flag(verbose_load,true),
ensure_loaded(library(make)),
findall(File, make:modified_file(File), Reload0),
list_to_set(Reload0, Reload),
update_changed_files_eggdrop(Reload))))),!.
update_changed_files_eggdrop([]):-sleep(0.005).
update_changed_files_eggdrop(Reload):-
( prolog:make_hook(before, Reload)
-> true
; true
),
print_message(silent, make(reload(Reload))),
make:maplist(reload_file, Reload),
print_message(silent, make(done(Reload))),
( prolog:make_hook(after, Reload)
-> true
;
true %(list_undefined,list_void_declarations)
),!.
% ===================================================================
% IRC OUTPUT
% ===================================================================
:-export(sayq/1).
%% sayq( ?D) is det.
%
% Sayq.
%
sayq(D):-sformat(S,'~q',[D]),!,say(S),!.
:-export(say/1).
%% say( ?D) is det.
%
% Say.
%
say(D):- t_l:default_channel(C),say(C,D),!.
say(D):- say("#logicmoo",D),!.
%% is_empty( ?A) is det.
%
% If Is A Empty.
%
is_empty(A):-egg_to_string(A,S),string_length(S,0).
%% get_session_prefix( ?ID) is det.
%
% Get Session Prefix.
%
get_session_prefix(ID):-t_l:session_id(ID),!.
get_session_prefix(ID):-t_l:default_user(ID),!.
get_session_prefix('').
%% put_server_count( ?Current) is det.
%
% Hook To [t_l:put_server_count/1] For Module Eggdrop.
% Put Server Count.
%
:-thread_local t_l: put_server_count/1.
:-thread_local t_l: put_server_no_max/0.
t_l:put_server_count(0).
%% check_put_server_count( ?Max) is det.
%
% Check Put Server Count.
%
check_put_server_count(0):- if_defined(t_l:put_server_no_max),retractall(t_l:put_server_count(_)),asserta(t_l:put_server_count(0)).
check_put_server_count(Max):-retract(t_l:put_server_count(Was)),Is is Was+1,asserta(t_l:put_server_count(Is)),!,Is =< Max.
%
%% to_egg( ?X) is det.
%
% Converted To Egg.
%
to_egg(X):-to_egg('~w',[X]),!.
%% to_egg( ?X, ?Y) is det.
%
% Converted To Egg.
%
to_egg(X,Y):-once(egg:stdio(_Agent,_InStream,OutStream)),once((sformat(S,X,Y),format(OutStream,'~s\n',[S]),!,flush_output_safe(OutStream))).
%% escape_quotes( ?LIST, ?ISO) is det.
%
% Escape Quotes.
%
escape_quotes(LIST,ISO):-
%dmsg(q(I)),
% term_string(I,IS),!,
%string_to_list(IS,LIST),!,
list_replace_egg(LIST,92,[92,92],LISTM),
list_replace_egg(LISTM,34,[92,34],LISTM2),
list_replace_egg(LISTM2,91,[92,91],LIST3),
list_replace_egg(LIST3,36,[92,36],LISTO),
=(LISTO,ISO),!.
% text_to_string(LISTO,ISO),!.
%% list_replace_egg( ?List, ?Char, ?Replace, ?NewList) is det.
%
% List Replace Egg.
%
list_replace_egg(List,Char,Replace,NewList):-
append(Left,[Char|Right],List),
append(Left,Replace,NewLeft),
list_replace_egg(Right,Char,Replace,NewRight),
append(NewLeft,NewRight,NewList),!.
list_replace_egg(List,_Char,_Replace,List):-!.
%% say(?Channel, ?List) is det.
%
% Say List.
%
:- export(say/2).
say(Channel,List):-
get_session_prefix(Prefix),!,
say(Channel,Prefix,List),!.
split_at(Text,At,LCodes,RCodes):- number(At),!, sub_atom(Text,0,At,_,LCodes),sub_atom(Text,At,_,0,RCodes),!.
split_at(Text,At,LCodes,RCodes):- sub_atom(Text,Before,1,_After,At),sub_atom(Text,0,Before,_,LCodes),sub_atom(Text,Before,_,0,RCodes),!.
%% flushed_privmsg( ?Channel, ?Fmt, ?Args) is det.
%
% Flushed Privmsg.
%
flushed_privmsg(Channel,Fmt,Args):-
format(string(NS),Fmt,Args),
privmsg(Channel,NS),!.
empty_prefix(''):-!.
empty_prefix(""):-!.
empty_prefix(``):-!.
%% say(+Channel, +Agent, ?List) is det.
%
% Say List.
%
:-export(say/3).
say(Channel:Prefix,_ID,List):-nonvar(Channel),!,say(Channel,Prefix,List).
say(Channel,Prefix,Data):- empty_prefix(Prefix),!,say(Channel,Channel,Data).
say(Channel,Prefix,Data):- empty_prefix(Channel),!,say(Prefix,Prefix,Data).
say(_Channel,_Prefix,Data):- empty_prefix(Data),!.
say(Channel,Prefix,[N|L]):- !,maplist(say(Channel,Prefix),[N|L]).
say(Channel,Prefix,Data):- (egg_to_string(Channel,S)-> Channel\==S),!,say(S,Prefix,Data).
say(Channel,Prefix,Data):- (egg_to_string(Prefix,S)-> Prefix\==S),!,say(Channel,S,Data).
say(Channel,Prefix,Data):- \+ string(Data), egg_to_string(Data, S)-> S\==Data,!,say(Channel,Prefix,S),!.
say(Channel,Prefix,Data):- \+ string(Data), sformat(SF,'~p',[Data]), say(Channel,Prefix,SF),!.
%say(Channel,Text):- my_wdmsg(will_say(Channel,Text)),fail.
% say(_,NonList,Data):-is_stream(NonList),!,say(NonList,"console",Data),!.
say(Channel,Prefix,Text):- split_at(Text,'\n',LCodes,RCodes), say(Channel,Prefix,LCodes), say(Channel,Prefix,RCodes).
say(Channel,_Prefix,Text):- privmsg(Channel,Text),!.
%say(Channel,Text):- my_wdmsg(will_say(Channel,Text)),fail.
%% privmsg( ?Channel, ?Text) is det.
%
% Privmsg Primary Helper.
%
privmsg(Channel,Text):-atom_length(Text,Len),Len>430,
split_at(Text,430,LCodes,RCodes),privmsg1(Channel,LCodes),!,privmsg(Channel,RCodes).
privmsg(Channel,Text):-privmsg1(Channel,Text).
/*
% privmsg2(Channel,Text):-on_f_log_ignore(format(OutStream,'\n.msg ~s ~s\n',[Channel,Text])).
% privmsg2(Channel,Text):- escape_quotes(Text,N),ignore(catch(format(OutStream,'\n.tcl putserv "PRIVMSG ~s :~s" ; return "noerror ."\n',[Channel,N]),_,fail)),!.
say(Agent,Prefix,Out):-sformat(SF,'~w: ~p',[Prefix,Out]), say(Agent,SF),!.
say(Channel,[Channel,': '|Data]):-nonvar(Data),say(Channel,Data),!.
must(flushed_privmsg(Channel,'~w: ~w',[Prefix,N])),
say(Channel,Prefix,L),!.
*/
%% privmsg1( ?Channel, ?Text) is det.
%
% Privmsg Secondary Helper.
%
privmsg1(Channel,Text):-check_put_server_count(30)->privmsg2(Channel,Text);
ignore(check_put_server_count(100)->privmsg_session(Channel,Text);true).
%% privmsg2( ?Channel, ?Text) is det.
%
% Privmsg Extended Helper.
%
privmsg2(Channel:_,Text):-nonvar(Channel),!,privmsg2(Channel,Text).
privmsg2(_:Channel,Text):-nonvar(Channel),!,privmsg2(Channel,Text).
privmsg2(Channel,Text):- sleep(0.2),escape_quotes(Text,N), to_egg('.tcl putquick "PRIVMSG ~s :~s"\n',[Channel,N]),!.
privmsg2(Channel,Text):- sleep(0.2), to_egg('.tcl putquick "PRIVMSG ~s :~w"\n',[Channel,Text]),!.
%% putnotice( ?Channel, ?Text) is det.
%
% Putnotice.
%
putnotice(Channel,Text):- escape_quotes(Text,N),to_egg('.tcl putserv "NOTICE ~s :~w"\n',[Channel,N]).
%% privmsg_session( ?Channel, ?Text) is det.
%
% Privmsg Session.
%
privmsg_session(Channel,Text):- t_l:session_id(ID),(ID==Channel->privmsg2(Channel,Text);privmsg2(ID,Text)).
% ===================================================================
% Startup
% ===================================================================
%% show_thread_exit is det.
%
% Show Thread Exit.
%
show_thread_exit:- my_wdmsg(warn(eggdrop_show_thread_exit)).
%% egg_go_fg is det.
%
% Egg Go Fg.
%
egg_go_fg:-
%deregister_unsafe_preds,
%set_prolog_flag(xpce,false),
%with_no_x
consultation_thread(swipl,3334).
%% egg_go is det.
%
% Egg Go.
%
% egg_go:- egg_go_fg,!.
egg_go:- thread_property(R,status(running)),R == egg_go,!.
egg_go:- thread_property(_,alias(egg_go)),threads,fail.
egg_go:- thread_create(egg_go_fg,_,[alias(egg_go),detached(true),an_exit(show_thread_exit)]).
egg_nogo:-thread_signal(egg_go,thread_exit(requested)).
/*
:- source_location(S,_),forall(source_file(H,S),ignore(( ( \+predicate_property(H,PP),member(PP,[(multifile),built_in]) ),
functor(H,F,A),module_transparent(F/A),export(F/A),user:import(H)))).
*/
%% read_one_term_egg( ?Stream, ?CMD, ?Vs) is det.
%
% Read One Term Egg.
%
:-export(read_one_term_egg/3).
:-module_transparent(read_one_term_egg/3).
read_one_term_egg(Stream,CMD,Vs):- \+ is_stream(Stream),l_open_input(Stream,InStream),!,
with_stream_pos(InStream,show_entry(read_one_term_egg(InStream,CMD,Vs))).
read_one_term_egg(Stream,CMD,_ ):- at_end_of_stream(Stream),!,CMD=end_of_file,!.
% read_one_term_egg(Stream,CMD,Vs):- catch((input_to_forms(Stream,CMD,Vs)),_,fail),CMD\==end_of_file,!.
read_one_term_egg(Stream,CMD,Vs):- catch((read_term(Stream,CMD,[variable_names(Vs)])),_,fail),CMD\==end_of_file,!.
read_one_term_egg(Stream,unreadable(String),_):-catch((read_stream_to_codes(Stream,Text),string_codes(String,Text)),_,fail),!.
read_one_term_egg(Stream,unreadable(String),_):-catch((read_pending_input(Stream,Text,[]),string_codes(String,Text)),_,fail),!.
:-export(read_each_term_egg/3).
:-module_transparent(read_each_term_egg/3).
%% read_each_term_egg( ?S, ?CMD, ?Vs) is det.
%
% Read Each Term Egg.
%
read_each_term_egg(S,CMD,Vs):-
show_failure(( l_open_input(S,Stream),
findall(CMD-Vs,(
repeat,
read_one_term_egg(Stream,CMD,Vs),
(CMD==end_of_file->!;true)),Results),!,
((member(CMD-Vs,Results),CMD\==end_of_file)*->true;read_one_term_egg(S,CMD,Vs)))).
%:- ensure_loaded(library(logicmoo/common_logic/common_logic_sexpr)).
%% read_egg_term( ?S, ?CMD, ?Vs) is nondet.
%
% Read Each Term Egg.
%
:-export(read_egg_term/3).
:-module_transparent(read_egg_term/3).
:- use_module(library(sexpr_reader)).
read_egg_term(S,CMD0,Vs0):- text_to_string(S,String),
split_string(String,""," \r\n\t",[SString]),
atom_concat(_,'.',SString),
open_string(SString,Stream),
findall(CMD0-Vs0,(
catch(read_term(Stream,CMD,[double_quotes(string),module(eggdrop),variable_names(Vs)]),_,fail),!,
((CMD=CMD0,Vs=Vs0);
read_egg_term_more(Stream,CMD0,Vs0))),List),!,
member(CMD0-Vs0,List).
read_egg_term(S,lispy(CMD),Vs):- text_to_string(S,String),
input_to_forms(String,CMD,Vs),!,is_list(CMD).
read_egg_term_more(Stream,CMD,Vs):-
repeat,
catch(read_term(Stream,CMD,[double_quotes(string),module(eggdrop),variable_names(Vs)]),_,CMD==err),
(CMD==err->(!,fail);true),
(CMD==end_of_file->!;true).
:- user:import(read_egg_term/3).
:- module_transparent((egg_go)/0).
:- module_transparent((egg_go_fg)/0).
:- module_transparent((show_thread_exit)/0).
:- module_transparent((list_replace_egg)/4).
:- module_transparent((escape_quotes)/2).
:- module_transparent((to_egg)/2).
:- module_transparent((to_egg)/1).
:- module_transparent((check_put_server_count)/1).
:- module_transparent((is_empty)/1).
:- module_transparent((get_session_prefix)/1).
:- module_transparent((say)/3).
:- module_transparent((say)/2).
:- module_transparent((say)/1).
:- module_transparent((sayq)/1).
:- module_transparent((update_changed_files_eggdrop)/0).
:- module_transparent((read_codes_and_send)/2).
:- module_transparent((read_from_agent_and_send)/2).
:- module_transparent((remove_anons)/2).
:- module_transparent((write_varcommas3)/1).
:- module_transparent((write_varcommas2)/1).
:- module_transparent((write_varvalues3)/1).
:- module_transparent((write_varvalues2)/1).
:- module_transparent((format_nv)/2).
:- module_transparent((vars_as_comma)/0).
:- module_transparent((vars_as_list)/0).
:- module_transparent((flush_all_output)/0).
:- module_transparent((cit3)/0).
:- module_transparent((cit2)/0).
:- module_transparent((cit)/0).
:- module_transparent((is_lisp_call_functor)/1).
:- module_transparent((add_maybe_static)/2).
:- module_transparent((close_ioe)/3).
:- module_transparent((eggdrop_bind_user_streams)/0).
:- module_transparent((unreadable)/1).
:- module_transparent((recordlast)/3).
:- module_transparent((ignored_channel)/1).
:- module_transparent((ignored_source)/1).
:- module_transparent((last_read_from)/3).
:- module_transparent((irc_receive)/5).
:- module_transparent((pubm)/5).
:- module_transparent((ctcp)/6).
:- module_transparent((msgm)/5).
:- module_transparent((join)/4).
:- module_transparent((part)/5).
:- module_transparent((get2react)/1).
:- module_transparent((consultation_codes)/3).
:- module_transparent((is_callable_egg)/1).
:- module_transparent((consultation_thread)/2).
:- module_transparent((eggdropConnect)/4).
:- module_transparent((eggdropConnect)/2).
:- module_transparent((eggdropConnect)/0).
:- module_transparent((deregister_unsafe_preds)/0).
:- module_transparent((remove_pred_egg)/3).
:- module_transparent((unsafe_preds_egg)/3).
:- module_transparent((my_wdmsg)/1).
:- module_transparent((ctrl_port)/1).
:- module_transparent((ctrl_pass)/1).
:- module_transparent((ctrl_nick)/1).
:- module_transparent((ctrl_server)/1).
:- module_transparent((bot_nick)/1).
:- module_transparent((write_v)/1).
:- module_transparent((source_and_module_for_agent)/3).
:- module_transparent((with_rl)/1).
:- module_transparent((with_no_input)/1).
:- module_transparent((with_io)/1).
:- module_transparent((with_input_channel_user)/3).
:- module_transparent((with_error_to_output)/1).
:- module_transparent((ignore_catch)/1).
:- module_transparent((call_in_thread)/1).
:- ignore((source_location(S,_),prolog_load_context(module,M),module_property(M,class(library)),
forall(source_file(M:H,S),
ignore((functor(H,F,A),
ignore(((\+ atom_concat('$',_,F),(export(F/A) , current_predicate(system:F/A)->true; system:import(M:F/A))))),
ignore(((\+ predicate_property(M:H,transparent), module_transparent(M:F/A), \+ atom_concat('__aux',_,F),debug(modules,'~N:- module_transparent((~q)/~q).~n',[F,A]))))))))).
:- source_location(S,_),prolog_load_context(module,M),
forall(source_file(M:H,S),ignore((functor(H,F,A),
nop((\+ mpred_database_term(F,A,_))),
F\=='$mode',
F\=='$pldoc',
ignore(((\+ atom_concat('$',_,F),export(F/A)))),
\+ predicate_property(M:H,transparent),
ignore(((\+ atom_concat('__aux',_,F),format('~N:- module_transparent((~q)/~q).~n',[F,A])))),
M:multifile(M:F/A),
M:module_transparent(M:F/A)))).
% :- ircEvent("dmiles","dmiles",say("(?- (a b c))")).
| TeamSPoon/logicmoo_workspace | packs_sys/eggdrop/prolog/eggdrop_next.pl | Perl | mit | 48,672 |
package FuseBead::From::PNG::View::JSON;
use strict;
use warnings;
BEGIN {
$FuseBead::From::PNG::VERSION = '0.02';
}
use parent qw(FuseBead::From::PNG::View);
use Data::Debug;
use JSON;
sub print {
my $self = shift;
my %args = ref $_[0] eq 'HASH' ? %{$_[0]} : @_;
return JSON->new->utf8->pretty->encode( \%args );
}
=pod
=head1 NAME
FuseBead::From::PNG::View::JSON - Format data returned from FuseBead::From::PNG
=head1 SYNOPSIS
use FuseBead::From::PNG;
my $object = FuseBead::From::PNG->new({ filename => 'my_png.png' });
$object->process(view => 'JSON'); # Data is returned as JSON
=head1 DESCRIPTION
Class to returned processed data in JSON format
=head1 USAGE
=head2 new
Usage : ->new()
Purpose : Returns FuseBead::From::PNG::View::JSON object
Returns : FuseBead::From::PNG::View::JSON object
Argument :
Throws :
Comment :
See Also :
=head2 print
Usage : ->print({}) or ->print(key1 => val1, key2 => val2)
Purpose : Returns JSON formated data (in utf8 and pretty format)
Returns : Returns JSON formated data (in utf8 and pretty format)
Argument :
Throws :
Comment :
See Also :
=head1 BUGS
=head1 SUPPORT
=head1 AUTHOR
Travis Chase
CPAN ID: GAUDEON
gaudeon@cpan.org
https://github.com/gaudeon/FuseBead-From-Png
=head1 COPYRIGHT
This program is free software licensed under the...
The MIT License
The full text of the license can be found in the
LICENSE file included with this module.
=head1 SEE ALSO
perl(1).
=cut
1;
| gaudeon/FuseBead-From-PNG | lib/FuseBead/From/PNG/View/JSON.pm | Perl | mit | 1,545 |
#! /usr/bin/perl -w
if(open LOG, ">>pl.log") {
# print LOG 'xxx';
select LOG;
print "xxxx\n";
} else {
print 'yyy';
} | yuweijun/learning-programming | language-perl/filehandle.pl | Perl | mit | 121 |
package Eixo::Docker::EventPool;
use strict;
use IO::Handle;
use JSON;
sub new{
return bless({
filter=>$_[1] || undef,
api=>$_[2],
frequency=>$_[3]
}, $_[0]);
}
sub create{
my ($self) = @_;
my ($reader, $writer);
pipe($reader, $writer);
$writer->autoflush(1);
if(my $pid = fork){
close($writer);
return {
pid=>$pid,
reader=>$reader
}
}
else{
$self->{writer} = $writer;
$SIG{TERM} = sub {
exit 0;
};
eval{
$self->loop;
};
if($@){
print "CRASHED : $@\n";
exit 1;
}
}
}
sub loop{
my ($self) = @_;
$self->{last} = time - 10;
while(1){
my $events = $self->__getEvents();
$self->__sendEvents($events);
}
}
sub __getEvents{
my ($self) = @_;
my $n_time = time + $self->{frequency};
my $events = $_[0]->{api}->events->get(
until=>$n_time,
since=>$self->{last}
);
$self->{last} = $n_time;
return $events;
}
sub __sendEvents{
my ($self, $events) = @_;
my $w = $self->{writer};
my $json = JSON->new;
foreach my $e (@{$events->{Events}}){
print $w $json->encode($e) . "\n";
}
$events->{Events} = [];
}
1;
| alambike/eixo-docker | lib/Eixo/Docker/EventPool.pm | Perl | apache-2.0 | 1,121 |
use v5.18;
$_ = <<'HERE';
Out "Top 'Middle "Bottom" Middle' Out"
HERE
my @matches;
say "Matched!" if m/
(?(DEFINE)
(?<QUOTE_MARK> ['"])
(?<NOT_QUOTE_MARK> [^'"])
(?<QUOTE>
(
(?<quote>(?"E_MARK))
(?:
(?&NOT_QUOTE_MARK)++
(?"E)
)*
\g{quote}
)
(?{ [ @{$^R}, $^N ] })
)
)
(?"E) (?{ @matches=@{ $^R } })
/x;
| mishin/presentation | regex_recursion/012.pl | Perl | apache-2.0 | 661 |
#! /usr/bin/perl
use warnings;
use strict;
use Time::HiRes qw( usleep ualarm gettimeofday tv_interval );
use Fcntl;
use File::Basename;
#-------------------------------------------------------------------
# Daniel Bolanos 2012
# Boulder Language Technologies
#
# description: accumulate statistics for Maximum Likelihood Estimation
#
# parameters:
#
#-------------------------------------------------------------------
# input parameters
my $mode = $ARGV[0];
my $filePhoneSet;
my $fileLexicon;
my $dirMLF;
my $fileHMMInput;
my $nphones;
my $optionalSymbols;
my $pronOpt;
my $dirFeatures;
my $dirFeaturesAli;
my $dirFeaturesAcc;
my $fileFeaturesConfig;
my $fileFeaturesConfigAli;
my $fileFeaturesConfigAcc;
my $covarianceAcc;
my $dirOutput;
# single-stream accumulation
if ($ARGV[0] eq "single") {
if ((scalar @ARGV) != 11) {
die("wrong number of parameters");
}
($mode,$filePhoneSet,$fileLexicon,$dirMLF,$fileHMMInput,$nphones,$optionalSymbols,$pronOpt,
$dirFeatures,$fileFeaturesConfig,$dirOutput) = @ARGV;
}
# double-stream accumulation (useful for single pass retraining)
elsif ($mode eq "double") {
if ((scalar @ARGV) != 14) {
die("wrong number of parameters");
}
($mode,$filePhoneSet,$fileLexicon,$dirMLF,$fileHMMInput,$nphones,$optionalSymbols,$pronOpt,
$dirFeaturesAli,$dirFeaturesAcc,$fileFeaturesConfigAli,$fileFeaturesConfigAcc,
$covarianceAcc,$dirOutput) = @ARGV;
} else {
die("unrecognized mode: \"$mode\"");
}
# auxiliar folders
my $dirTemp = "$dirOutput/tmp";
my $dirAccumulators = "$dirOutput/acc";
my $dirTrainingOutput = "$dirOutput/out";
# create the auxiliar folders
system("mkdir -p $dirTemp");
system("mkdir -p $dirAccumulators");
system("mkdir -p $dirTrainingOutput");
# process each of the segments
opendir(DIR_MLF,"$dirMLF") || die("unable to open the folder: $dirMLF");
my @filesMLF = grep(/\.txt/,readdir(DIR_MLF));
foreach my $fileMLF (sort @filesMLF) {
# semaphore for exclusive processing of mlf segments
my $fileTemp = "$dirTemp/$fileMLF";
if (! defined(sysopen(FILE, $fileTemp, O_WRONLY|O_CREAT|O_EXCL))) {
next;
}
close(FILE);
my $base = ($fileMLF =~ m/(.+)\./)[0];
my $fileOutput = "$dirTrainingOutput/$base\.out\.txt";
my $fileError = "$dirTrainingOutput/$base\.err\.txt";
my $fileMLFPath = "$dirMLF/$fileMLF";
my $fileAcc = "$dirAccumulators/$base\.bin";
my $context = "";
if ($nphones ne "physical") {
$context = "-ww $nphones -cw $nphones";
}
my $fillersPron = "";
if ($optionalSymbols ne "no") {
$fillersPron .= "-opt $optionalSymbols";
}
if ($pronOpt eq "yes") {
$fillersPron .= " -pro yes";
}
# single-stream accumulation
if ($mode eq "single") {
system("mlaccumulator -pho \"$filePhoneSet\" -mod \"$fileHMMInput\" -lex \"$fileLexicon\" -fea \"$dirFeatures\" -cfg \"$fileFeaturesConfig\" -mlf \"$fileMLFPath\" $context $fillersPron -dAcc \"$fileAcc\" 1> $fileOutput 2> $fileError");
}
# double-stream accumulation
elsif ($mode eq "double") {
system("mlaccumulator -pho \"$filePhoneSet\" -mod \"$fileHMMInput\" -lex \"$fileLexicon\" -fea \"$dirFeaturesAli\" -feaA \"$dirFeaturesAcc\" -cfg \"$fileFeaturesConfigAli\" -cfgA \"$fileFeaturesConfigAcc\" -covA $covarianceAcc -mlf \"$fileMLFPath\" $context $fillersPron -dAcc \"$fileAcc\" 1> $fileOutput 2> $fileError");
}
}
closedir(DIR_MLF);
| nlphacker/bavieca | scripts/accumulate.pl | Perl | apache-2.0 | 3,321 |
package Paws::CloudDirectory::RuleParameterMap;
use Moose;
with 'Paws::API::StrToNativeMapParser';
has Map => (is => 'ro', isa => 'HashRef[Maybe[Str]]');
1;
### main pod documentation begin ###
=head1 NAME
Paws::CloudDirectory::RuleParameterMap
=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::RuleParameterMap object:
$service_obj->Method(Att1 => { key1 => $value, ..., keyN => $value });
=head3 Results returned from an API call
Use accessors for each attribute. If Att1 is expected to be an Paws::CloudDirectory::RuleParameterMap object:
$result = $service_obj->Method(...);
$result->Att1->Map->{ key1 }
=head1 DESCRIPTION
This class has no description
=head1 ATTRIBUTES
=head2 Map => Str
Use the Map method to retrieve a HashRef to the map
=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/RuleParameterMap.pm | Perl | apache-2.0 | 1,366 |
#
# Copyright 2015 Electric Cloud, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
####################################################################
#
# ECGerrit
# A perl package to encapsulate the interaction with the
# gerrit code review tool
#
####################################################################
package ECGerrit;
$::gApproveCmd = "review";
$::gTableCase = '';
$|=1;
my $pluginKey = '{$pluginKey}';
my $pluginName = "@PLUGIN_NAME@";
my $pluginVersion = '{$pluginVersion}';
# get JSON from the plugin directory
if ("$ENV{COMMANDER_PLUGIN_PERL}" ne "") {
# during tests
push @INC, "$ENV{COMMANDER_PLUGIN_PERL}";
} else {
# during production
push @INC, "$ENV{COMMANDER_PLUGINS}/ $pluginName /agent/perl";
}
require JSON;
use URI::Escape;
use Net::SSH2;
use File::Basename;
use IO::Socket;
use MIME::Base64;
use ElectricCommander;
use ElectricCommander::PropDB;
####################################################################
# Object constructor for ECGerrit
#
# Inputs
# sshurl = the gerrit server (ssh://user@host:port)
# dbg = debug level (0-3)
####################################################################
sub new {
my $class = shift;
my $self = {
_cmdr => shift,
_user => shift,
_server => shift,
_port => shift,
_ssh_pub => shift,
_ssh_pvt => shift,
_dbg => shift,
};
bless ($self, $class);
return $self;
}
######################################
# getCmdr
#
# Get the commander object
######################################
sub getCmdr {
my $self = shift;
return $self->{_cmdr};
}
######################################
# getServer
#
# Get the server
######################################
sub getServer {
my $self = shift;
if (!defined $self->{_server} ||
$self->{_server} eq "") {
# default to localhost
return "localhost";
} else {
return $self->{_server};
}
}
######################################
# getUser
#
# Get the user
######################################
sub getUser {
my $self = shift;
if (!defined $self->{_user} ||
$self->{_user} eq "") {
# default to commander
return "commander";
} else {
return $self->{_user};
}
}
######################################
# getPort
#
# Get the Port
######################################
sub getPort {
my $self = shift;
if (!defined $self->{_port} ||
$self->{_port} eq "") {
# default to gerrit default
return "29418";
} else {
return $self->{_port};
}
}
######################################
# getSSHPvt
#
# Get the Port
######################################
sub getSSHPvt {
my $self = shift;
return $self->{_ssh_pvt};
}
######################################
# getSSHPub
#
# Get the Port
######################################
sub getSSHPub {
my $self = shift;
return $self->{_ssh_pub};
}
######################################
# getDbg
#
# Get the Dbg level
######################################
sub getDbg {
my $self = shift;
if (!defined $self->{_dbg} ||
$self->{_dbg} eq "") {
return 0;
} else {
return $self->{_dbg};
}
}
######################################
# gerrit_db_query
#
# parse output of gerrit db query
#
# Gerrit queries are run through the
# ssh host gerrit gsql command which
# returns data in JSON format.
#
# Depending on the query, results could
# be large (too large to hold in mem)
# so be carefull with the query
#
# args
# opertation = a SQL string
#
# returns
# results - array of results
#
# example
# my ($exit,@results) = $self->gerrit_db_query("SELECT * FROM ACCOUNTS;");
# print @results[0]->{columns}{ssh_user_name};
#
######################################
sub gerrit_db_query {
my $self = shift;
my $operation = shift;
my @sqlout = ();
my $gcmd = "gerrit gsql --format JSON";
my $input = "$operation\n\\q\n";
#my $input = "$operation";
$self->debugMsg(3,"========command =========");
$self->debugMsg(3, $operation);
$self->debugMsg(3,"========raw output ======");
my ($exit,$out) = $self->runCmd("$gcmd","$input");
if ($exit != 0 ) {
# if command did not succeed we should exit
# this is drastic, but if query command is not working
# something fundamental is wrong with setup
$self->showMsg("$out");
$self->showError("error running command $gcmd ($exit)");
}
$self->debugMsg(3, $out);
my $row = 0;
my (@lines) = split(/\n/,$out);
foreach my $line (@lines) {
my $json = JSON->new->utf8;
my $arr = $json->decode($line);
push @sqlout, $arr;
$row++;
}
# remove the statistics record
# {"type":"query-stats","rowCount":3,"runTimeMilliseconds":1}
if (scalar(@sqlout) > 0) {
pop @sqlout;
}
$self->debugMsg(3, "table found $row rows");
return @sqlout;
}
##########################################
# trimstr
# trim leading and trailing whitespace
#
# args
# intput string
#
# returns
# trimmed output string
##########################################
sub trimstr {
my $self = shift;
my $string = shift;
$string =~ s/^\s+//;
$string =~ s/\s+$//;
return $string;
}
##########################################
# getChangeComments
# get the comments for a change
#
# args
# change - change id
#
# returns
# table - table of results
#
##########################################
sub getChangeComments {
my $self = shift;
my $changeid = shift;
my @empty = ();
if (!defined $changeid || "$changeid" eq "") {
$self->showError("no changeid passed to getChangeComments");
return @empty;
}
# must have something after MESSAGE or the limited parser will not work
return ($self->gerrit_db_query(
"select MESSAGE,UUID from ". $self->t('CHANGE_MESSAGES') ." where CHANGE_ID = '$changeid';"));
}
##########################################
# getAccountId
# get the AccountId for the gerrit user
#
# args
# user - user name
#
# returns
# id - numeric AccountId or user
#
##########################################
sub getAccountId {
my $self = shift;
my $user = shift;
if (!defined $user || "$user" eq "") {
$self->showError ("no user passed to getUserId");
return undef;
}
my @tmp = $self->gerrit_db_query(
"select ACCOUNT_ID from ". $self->t('ACCOUNTS'). " where SSH_USER_NAME = '$user';");
if (scalar(@tmp) == 0 || "$tmp[0]->{columns}{account_id}" eq "") {
$self->showError( "No account found for user $user.");
return "";
}
return $tmp[0]->{columns}{account_id};
}
##########################################
# getTime
# format at time string
#
# args
# none
#
# returns
# time string
##########################################
sub getTime {
my $self = shift;
my $string;
my ($sec,$min,$hour,$mday,$mon,$year,$wday,
$yday,$isdst)=localtime(time);
$string = sprintf( "%4d-%02d-%02d %02d:%02d:%02.3f",
$year+1900,$mon+1,$mday,$hour,$min,$sec);
return $string;
}
##########################################
# computeUUID
# key field for messages is a computed
# uuid based on the sequence
# CHANGE_MESSAGE_ID. This computes the
# uuid string
#
# NOT NEEDED NOW THAT WE ARE USING COMMAND LINE
# FOR APPROVALS. LEFT HERE IN CASE WE NEED IT
# AGAIN
#
# args
# key - numeric key value
#
# returns
# uuid string
##########################################
sub computeUUID {
my $self = shift;
my $key = shift;
my $seq=0x7FFFFFFF;
my $num = pack('NN',$key,$seq);
my $string = encode_base64($num);
chomp $string;
return $string;
}
###################################################
# getOpenChanges
#
# Get a list of open changes for this
# project/branch
#
# args
# project - project of interest (optional)
# branch - branch of interest
#
# returns
# result - array from query results
###################################################
sub getOpenChanges {
my ($self,$proj,$branch) = @_;
my @result;
my $destbranch = "refs/heads/$branch";
my $query = "SELECT * from ". $self->t('CHANGES') ." WHERE"
. " DEST_BRANCH_NAME = '$destbranch'"
. " AND OPEN = 'Y'";
if ("$proj" ne "") {
$query .= " AND DEST_PROJECT_NAME = '$proj'";
}
$query .= ";";
return ($self->gerrit_db_query($query));
}
###################################################
# getOpenChangesFromManifest
#
# Get a list of open changes for a list of
# projects/branches
#
# args
# array of project:branches strings (separated by colon)
#
#
# returns
# result - array from query results
# change log: renamed from getOpenChangesForTeamBuild
###################################################
sub getOpenChangesFromManifest {
my ($self,@projects_branches) = @_;
my @result;
my $query = "SELECT * from ". $self->t('CHANGES') ." WHERE (";
my $i = 0;
my $size = scalar @projects_branches;
foreach my $manifest_project (@projects_branches) {
@info = split /:/, $manifest_project;
my $manifest_size = scalar @info;
my $using_change_id_only = 0;
my $proj = "";
my $branch = "";
my $change_id = "";
if ($manifest_size == 3){
$change_id = @info[0];
$proj = @info[1];
$branch = @info[2];
} elsif ( $manifest_size == 1){
$change_id = @info[0];
$using_change_id_only = 1;
}else {
$proj = @info[0];
$branch = @info[1];
}
chomp $proj, $branch, $change_id;
my $destbranch = "refs/heads/$branch";
if (($i > 0) && ($i < $size)) {
$query .= "\n OR \n";
}
$i++;
$query .= "(";
if ( ("$branch" ne "") && ("$change_id" eq "") ) {
$query .= "DEST_BRANCH_NAME = '$destbranch'"
}
# . " AND OPEN = 'Y'"; }
if ( ("$proj" ne "") && ("$change_id" eq "") ) {
$query .= " AND DEST_PROJECT_NAME = '$proj'";
}
if ("$change_id" ne "") {
if ($self->is_int($change_id) ){ #check if change_id is int
$query .= "CHANGE_ID = '$change_id'";
} else {
$query .= "CHANGE_KEY = '$change_id'";
}
}
$query .= " AND OPEN = 'Y')";
}
$query .= ');';
return ($self->gerrit_db_query($query));
}
################################################
# testECState
#
# Tests if a change/patchid has been marked in a
# particualr state by the commander integration
# This is done by looking in the comments.
# The EC integration will add comments to
# document what has been done.
#
# comment form
# ec:change:patch:state notes
#
# Examples:
# job run for this patchid
# ec:1:1:jobRunning 3453 http://....
#
# job finished for this patchid
# ec:1:1:jobComplete success http://...
#
# args
# changeid - numeric changeid
# patchid - numeric patchid
# state - state to test
# valid: jobAvailable jobRunning jobComplete
#
# returns
# 0 - not found
# uuid of CHANGE_MESSAGES row if found
#
#################################################
sub testECState {
my $self = shift;
my $changeid = shift;
my $patchid = shift;
my $state = shift;
$self->debugMsg(2, "testECState...c=$changeid p=$patchid s=$state");
if (!defined $changeid || !defined $patchid || !defined $state ||
"$changeid" eq "" || "$patchid" eq "" ) {
$self->showError("bad arguments to testECState");
return 0;
}
# get all comments for this changeset
# comments are not indexed by patchid
my @changes = $self->getChangeComments($changeid) ;
if (!@changes) {
return 0;
}
# look for magic string
my $numComments = scalar(@changes);
foreach my $row (@changes) {
my $msg = $row->{columns}{message};
if ($msg =~ m/ec\:$changeid\:$patchid\:$state/) {
$self->debugMsg(2, "testECState found state set");
# $row->{columns}{uuid} from gerrit 2.2.0 is a string like "AAAAAX///7c=" which result in 0 when adding to a number. so return 1 explicitly.
return 1;
}
}
$self->debugMsg(2, "testECState found state not set");
return 0;
}
################################################
# setECState
#
# marks a change/patchid for commander integration
#
# comment form
# ec:change:patch:state notes
#
# args
# project - gerrit project
# changeid - numeric changeid
# patchid - numeric patchid
# state - state to add
# valid: jobRunning jobComplete jobAvailable
# notes - other text to include in message
# category - the category for approve (optional)
# value o - the value for approve (optional)
#
#################################################
sub setECState {
my $self = shift;
my $project = shift;
my $changeid = shift;
my $patchid = shift;
my $state = shift;
my $notes = shift;
my $category = shift || "";
my $value = shift || "";
$self->debugMsg(1,"setECState...$changeid,$patchid s=$state n=$notes c=$category v=$value");
if (!defined $self || !defined $changeid ||
!defined $patchid || !defined $state ||
"$changeid" eq "" || "$patchid" eq "" || \
"$state" eq "") {
$self->showError( "bad arguments to setECState");
return 0;
}
my $result;
my $msg = "$notes ec:$changeid:$patchid:$state";
my $exit = $self->approve($project,$changeid, $patchid,$msg,$category,$value);
if ($exit) {
print "Error: Failed to set state '$state' on $changeid:$patchid\n";
exit $exit;
}
return 0;
}
#################################################
#################################################
# team_build
#################################################
#################################################
sub team_build {
my ($self, $rules, $filename) = @_;
$rules =~ s/^'//g;
$rules =~ s/'$//g;
$self->debugMsg(2,"rules:$rules");
my ($filters,$actions) = $self->parseRules($rules);
@project_branches = $self->parseManifest($filename);
#my @changes = $self->getOpenChanges($project,$branch);
#my @changes = $self->getOpenChangesForTeamBuild(@project_branches);
my @changes = $self->getOpenChangesFromManifest(@project_branches);
my ($metrics,$idmap) = $self->get_team_build_metrics(@changes);
my @eligible = $self->get_eligible_changes($filters,$metrics,$idmap);
if ($self->getDbg()) {
$self->print_filters($filters);
$self->print_actions($actions);
$self->print_metrics($metrics);
$self->print_changes(@changes);
$self->print_idmap($idmap);
$self->print_eligible(@eligible);
}
return @eligible;
}
#################################################
#################################################
# custom_build
#################################################
#################################################
sub custom_build {
my ($self, $rules, $manifest) = @_;
$rules =~ s/^'//g;
$rules =~ s/'$//g;
$self->debugMsg(2,"rules:$rules");
my ($filters,$actions) = $self->parseRules($rules);
@project_branches = $self->parseManifestStr($manifest);
#my @changes = $self->getOpenChangesForTeamBuild(@project_branches);
my @changes = $self->getOpenChangesFromManifest(@project_branches);
my ($metrics,$idmap) = $self->get_team_build_metrics(@changes);
my @eligible = $self->get_eligible_changes($filters,$metrics,$idmap);
if ($self->getDbg()) {
$self->print_filters($filters);
$self->print_actions($actions);
$self->print_metrics($metrics);
$self->print_changes(@changes);
$self->print_idmap($idmap);
$self->print_eligible(@eligible);
}
return @eligible;
}
#################################################
# team_appprove
#################################################
sub team_approve {
my ($self,$changes,$rules,$msg) = @_;
return $self->team_approve_base($changes, $rules, "SUCCESS",$msg);
}
#################################################
# team_annotate
#################################################
sub team_annotate {
my ($self,$changes,$msg) = @_;
#my @temp_changes = @$changes;
return $self->team_approve_base($changes, "", "",$msg);
}
#################################################
# team_disappprove
#################################################
sub team_disapprove {
my ($self,$changes,$rules,$msg) = @_;
return $self->team_approve_base($changes, $rules, "ERROR",$msg);
}
#################################################
# team_approve_base
#################################################
sub team_approve_base {
my ($self,$changes,$rules, $state, $msg) = @_;
my @temp_changes = @$changes;
my $category = "";
my $value = "";
if ("$rules" ne "") {
my ($filters,$actions) = $self->parseRules($rules);
# lookup the category, value, and user from the
# team_build_rules
$category = $actions->{$state}{CAT};
$value = $actions->{$state}{VAL};
}
$self->debugMsg(2,"approve");
$self->debugMsg(2,"category = $category");
$self->debugMsg(2,"value = $value");
foreach my $str (@temp_changes) {
my ($changeid, $patchid,$project) = split (/:/,$str);
$self->approve($project, $changeid, $patchid, $msg, $category,$value);
}
return ;
}
##########################################
# approve
# add comment and/or set approval
# using gerrit approve command
#
# args
# project - the project (optional)
# changeid - the changeset id
# patchid - the patchset id
# msg - the message to include
# category - the CATEGORY to set in approval (optional)
# value - the value to set (optional)
#
# returns
# exit code of running approve command
##########################################
sub approve {
my ($self,$project, $changeid, $patchid, $msg, $category,$value) = @_;
my $gcmd = "gerrit $::gApproveCmd $changeid,$patchid '--message=$msg'";
if ($project && "$project" ne "") {
$gcmd .= " '--project=$project'";
}
if ($category eq "SUBM") {
$gcmd .= " --submit ";
} else {
if ($category) {
$gcmd .= " --label $category=$value";
}
}
$self->debugMsg(2,"approve cmd:$gcmd");
# run the approve command
my ($exit,$out) = $self->runCmd($gcmd,"");
$self->showMsg($out);
return $exit;
}
#################################################
# get_eligible_changes
#
# process filters, changes, and metrics to
# pull out the set of changes that should
# be built
#
# Inputs
# changes - list of candidate changes
# filters- map of user specified filters
# metrics - map of user/category/min/max/counts
#
# Return
# list of change:patch numbers that should be built
#
#################################################
sub get_eligible_changes {
my ($self,$filters, $metrics,$idmap) = @_;
my @eligble;
foreach my $changeid (sort {$a<=>$b} keys % {$metrics}) {
# check filters against metrics
$self->debugMsg(1, "---Checking change $changeid against filters ---");
if ($self->check_filters($filters, $metrics->{$changeid} )) {
## add change/patch to eligible list
my $patchid = $idmap->{$changeid}{patchid};
my $project = $idmap->{$changeid}{project};
$self->debugMsg(1, "...hit $changeid:$patchid");
push (@eligible, "$changeid:$patchid:$project");
} else {
$self->debugMsg(1, "...miss $changeid:$patchid");
}
}
return @eligible;
}
#################################################
# get_team_build_metrics
#
# Search through comments for a project, branch
# and find max/min/count of different category
# comments
#
# Input
# filters - map of filters
#################################################
sub get_team_build_metrics {
my ($self,@changes) = @_;
my $metrics = ();
my $idmap = ();
foreach my $change (@changes) {
my $changeid = $change->{columns}{change_id};
my $project = $change->{columns}{dest_project_name};
my @max = $self->gerrit_db_query("SELECT MAX(PATCH_SET_ID) FROM "
. $self->t('PATCH_SETS') ." WHERE CHANGE_ID = '$changeid';");
my $patchid = $max[0]->{columns}{'max(patch_set_id)'};
$idmap->{$changeid}{patchid} = "$patchid";
$idmap->{$changeid}{project} = "$project";
$metrics->{$changeid}{""}{$cat}{COUNT} = 0;
$metrics->{$changeid}{""}{$cat}{MAX} = 0;
$metrics->{$changeid}{""}{$cat}{MIN} = 0;
# find all approvals for highest patchset for change
my @approvals = $self->gerrit_db_query("SELECT * FROM " . $self->t('PATCH_SET_APPROVALS') . " WHERE CHANGE_OPEN = 'Y'"
. " AND CHANGE_ID = '$changeid' AND PATCH_SET_ID = '$patchid';");
foreach my $approval (@approvals) {
my $cat = $approval->{columns}{category_id};
my $user = $self->get_user($approval->{columns}{account_id} );
my $value = $approval->{columns}{value};
$metrics->{$changeid}{""}{$cat}{COUNT} += 1;
if (!defined $metrics->{$changeid}{""}{$cat}{MIN} ||
$value < $metrics->{$changeid}{""}{$cat}{MIN} ) {
$metrics->{$changeid}{""}{$cat}{MIN} = $value;
}
if (!defined $metrics->{$changeid}{""}{$cat}{MAX} ||
$value > $metrics->{$changeid}{""}{$cat}{MAX} ) {
$metrics->{$changeid}{""}{$cat}{MAX} = $value;
}
$metrics->{$changeid}{$user}{$cat}{COUNT} += 1;
if (!defined $metrics->{$changeid}{$user}{$cat}{MIN} ||
$value < $metrics->{$changeid}{$user}{$cat}{MIN} ) {
$metrics->{$changeid}{$user}{$cat}{MIN} = $value;
}
if (!defined $metrics->{$changeid}{$user}{$cat}{MAX} ||
$value > $metrics->{$changeid}{$user}{$cat}{MAX} ) {
$metrics->{$changeid}{$user}{$cat}{MAX}= $value;
}
}
}
return ($metrics,$idmap);
}
############################################################
# check_filters
#
# Process filters with metrics to see if rules in
# filters pass. If they do, return 1, otherwise
# return 0
#
# Input
# filters and metrics maps
# Returns
# 1 if all filters pass, 0 otherwies
############################################################
sub check_filters {
my ($self,$filters, $metrics) = @_;
# for each filter
my $result = 1;
foreach my $num (sort keys % {$filters}) {
if ($filters->{$num}{TYPE} =~ /MAX/) {
$result = $self->check_max($filters->{$num},$metrics);
}
if ($filters->{$num}{TYPE} =~ /MIN/) {
$result = $self->check_min($filters->{$num},$metrics);
}
if ($filters->{$num}{TYPE} =~ /COUNT/) {
$result = $self->check_count($filters->{$num},$metrics);
}
if (!$result) { last; }
}
return $result;
}
############################################################
# check_max
#
# Check a filter of type max
#
# Input
# fitlers map
# metrics map
# Returns
# 1 if filter pass, 0 otherwies
############################################################
sub check_max {
my ($self,$filter,$metrics) = @_;
my $cat = $filter->{CAT};
my $op = $filter->{OP};
my $val = $filter->{VAL};
my $user_op = $filter->{USER_OP};
my $user = $filter->{USER};
# get the maximum value
my $max = 0;
if ("$user_op" eq "") {
$max = $metrics->{""}{$cat}{MAX} || 0;
} elsif ($user_op eq "eq") {
$max = $metrics->{$user}{$cat}{MAX} || 0;
} elsif ($user_op eq "ne") {
# take max of all users except $user
my $usermax = undef;
foreach my $ruser (keys % {$metrics}) {
# skip the ne user
if ($ruser = "$user") { next;}
if (!defined $usermax || $metrics->{$user}{$cat}{MAX} > $usermax ) {
$usermax = $metrics->{$user}{$cat}{MAX} || 0;
}
}
$max = $usermax;
}
# check max against filter
my $expr = "$max $op $val";
my $result = eval $expr;
$self->debugMsg(1,"...MAX $cat $op $val $user_op $user , max=$max, result=$result");
return $result;
}
############################################################
# check_min
#
# Check a filter of type min
#
# Input
# fitlers map
# metrics map
# Returns
# 1 if filter pass, 0 otherwies
############################################################
sub check_min {
my ($self,$filter,$metrics) = @_;
my $cat = $filter->{CAT};
my $op = $filter->{OP};
my $val = $filter->{VAL};
my $user_op = $filter->{USER_OP};
my $user = $filter->{USER};
# get the maximum value
my $min = 0;
if ("$user_op" eq "") {
$min = $metrics->{""}{$cat}{MIN} || 0;
} elsif ($user_op eq "eq") {
$min = $metrics->{$user}{$cat}{MIN} || 0;
} elsif ($user_op eq "ne") {
# take min of all users except $user
my $usermin = undef;
foreach my $ruser (keys % {$metrics}) {
# skip the ne user
if ($ruser = "$user") { next;}
if (!defined $usermin || $metrics->{$user}{$cat}{MIN} < $usermax ) {
$usermin = $metrics->{$user}{$cat}{MIN} || 0;
}
}
$min = $usermin;
}
# check min against filter
my $expr = "$min $op $val";
my $result = eval $expr;
$self->debugMsg(1,"...MIN $cat $op $val $user_op $user , min=$min, result=$result");
return $result;
}
############################################################
# check_count
#
# Check a filter of type count
#
# Input
# fitlers map
# metrics map
# Returns
# 1 if filter pass, 0 otherwies
############################################################
sub check_count {
my ($self,$filter,$metrics) = @_;
my $cat = $filter->{CAT};
my $op = $filter->{OP};
my $val = $filter->{VAL};
my $user_op = $filter->{USER_OP};
my $user = $filter->{USER};
# get the count value
my $count = 0;
if ("$user_op" eq "") {
$count = $metrics->{""}{$cat}{COUNT} || 0;
} elsif ($user_op eq "eq") {
$count = $metrics->{$user}{$cat}{COUNT} || 0;
} elsif ($user_op eq "ne") {
# take max of all users except $user
my $usercount = 0;
foreach my $ruser (keys % {$metrics}) {
# skip the ne user
if ($ruser = "$user") { next;}
$usercount += $metrics->{$user}{$cat}{COUNT} || 0;
}
$count = $usercount;
}
# check max against filter
my $expr = "$count $op $val";
my $result = eval $expr;
$self->debugMsg(1,"...COUNT $cat $op $val $user_op $user , count=$count, result=$result");
return $result;
}
############################################################
# get_user
#
# finds the ssh user name for a given account_id
#
# Args:
# id - a gerrit account id
#
# Returns
# string - the ssh_user configured for the account_id
############################################################
sub get_user {
my ($self,$id) = @_;
#Reference: https://groups.google.com/forum/#!topic/repo-discuss/b_enE_dXrOI
my @accounts = $self->gerrit_db_query("SELECT EXTERNAL_ID FROM ". $self->t('ACCOUNT_EXTERNAL_IDS')." WHERE ACCOUNT_ID = '$id' AND EXTERNAL_ID LIKE 'username:%';");
if (scalar(@accounts) == 0 || !$accounts[0]->{columns}{external_id}) {
$self->showError("No account found for user $id.");
return "";
}
my $user = $accounts[0]->{columns}{external_id};
$user =~ m/^username:(.+)/;
$user = $1;
$self->debugMsg(3,"id=$id user=$user");
return $user;
}
############################################################
# get_category_name
#
# finds the category name from category id
#
# Args:
# id - a category id
#
# Returns
# string - the category name suitable as an approve option
# it is all lowercase with spaces converted to -
############################################################
sub get_category_name {
my ($self,$id) = @_;
my @cats = $self->gerrit_db_query("SELECT NAME FROM " . $self->t('APPROVAL_CATEGORIES') . " WHERE CATEGORY_ID = '$id';");
if (scalar(@cats) == 0 || "$cats[0]->{columns}{name}" eq "") {
$self->showError("No category name for id $id.");
return "";
}
my $name = $cats[0]->{columns}{name};
$name =~ s/ /-/g;
$name = lc ($name);
$self->debugMsg(3,"id=$id name=$name");
return $name;
}
############################################################
# parseRules
#
# read in a blob of config text and parse into
# filter and action maps
#
# Args:
# blob - string to process
#
# Returns
# filters,actions maps
############################################################
sub parseRules {
my ($self,$blob) = @_;
my $filters = ();
my $actions = ();
my @lines = split (/\n/,$blob);
my $num = 0;
$self->debugMsg(3,"parsing rules:$blob");
foreach my $line (@lines ) {
if ($line =~ /^#/) { next;}
if ($line =~ /^[\s]*$/) { next;}
my @tokens = split (/ /, $line);
if ($line =~ /^FILTER/) {
my $type = @tokens[1];
my $cat = @tokens[2];
my $op = @tokens[3];
my $val = @tokens[4];
my $userflg = @tokens[5];
my $user_op = @tokens[6];
my $user = @tokens[7];
$self->debugMsg(3,"parsing FILTER:$type $cat $op $val $user_op $user");
if ("$type" ne "MAX" && "$type" ne "MIN" &&
"$type" ne "COUNT" ) {
$self->showError("FILTER ($type) must be MAX, MIN, or COUNT");
$self->showError($line);
next;
}
if ("$op" ne "ge" && "$op" ne "eq" &&
"$op" ne "gt" && "$op" ne "lt" &&
"$op" ne "le" && "$op" ne "ne") {
$self->showError("FILTER operation ($op) must be one of:eq ne lt le gt ge");
$self->showError($line);
next;
}
if ("$val" eq "" ) {
$self->showError("FILTER value is blank.");
$self->showError($line);
next;
}
if ("$userflg" eq "USER" ) {
if ("$user_op" ne "eq" && "$user_op" ne "ne") {
$self->showError("USER op ($user_op) must be one of:eq ne");
$self->showError($line);
next;
}
if ("$user" eq "") {
$self->showError("user name not found");
$self->showError($line);
next;
}
}
$filters->{$num}{TYPE} = $type;
$filters->{$num}{TYPE} = $type;
$filters->{$num}{CAT} = $cat;
$filters->{$num}{OP} = $op;
$filters->{$num}{VAL} = $val;
$filters->{$num}{USER_OP} = $user_op;
$filters->{$num}{USER} = $user;
$num++;
}
if ($line =~ /^ACTION/) {
my $state = @tokens[1];
my $cat = @tokens[2];
my $val = @tokens[3];
$self->debugMsg(3, "parsing ACTION:$state $cat $val");
if ("$state" ne "ERROR" && "$state" ne "SUCCESS") {
$self->showError("ACTION ($state) must be SUCCESS or ERROR");
$self->showError($line);
next;
}
if ("$cat" eq "" || "$val" eq "" ) {
$self->showError("ACTION category and value are required");
$self->showError($line);
next;
}
$actions->{$state}{CAT} = $cat;
$actions->{$state}{VAL} = $val;
}
}
return ($filters,$actions);
}
############################################################
# parseManifest
#
# read projects and branches from file to be used by the scan
# function
#
# Args:
# filename
#
# Returns
# hash with the pairs project branch name
############################################################
sub parseManifest{
my ($self,$fileName) = @_;
if ($::gRunCmdUseFakeOutput){
my @fakeOutput = ("platform/cts:master");
return @fakeOutput;
}
$self->debugMsg(3,"Parsing manifest file:$fileName");
open FILE, $fileName or die "Error: Could not open the manifest file, check the path in the configuration settings";
my @lines = <FILE>;
my @output;
my $size = scalar @lines;
my $c = 0;
foreach $line (@lines){
chomp($line);
if ($line ne ""){
@info = split ":", $line;
my $info_size = scalar @info;
if ( ($info_size == 3) || ($info_size == 2) || ($info_size == 1) ) {
@output[$c] = $line;
$c++;
}
}
}
#the file is empty we send the default values
if ($size <= 0){
@output[0] =":master";
}
close (FILE);
return @output;
}
############################################################
# parseManifestStr
#
# read projects and branches from file to be used by the scan
# function
#
# Args:
# manifest str
#
# Returns
# hash with the pairs project branch name
############################################################
sub parseManifestStr{
my ($self,$manifest_str) = @_;
if ($manifest_str ne ""){
$self->debugMsg(3,"Parsing manifest: $manifest_str");
}
my @lines = split(/\n/, $manifest_str);
my @output;
my $size = scalar @lines;
my $c = 0;
foreach $line (@lines){
chomp($line);
if ($line ne ""){
@info = split ":", $line;
my $info_size = scalar @info;
if ( ($info_size == 3) || ($info_size == 2) || ($info_size == 1) ){
@output[$c] = $line;
$c++;
}
}
}
#the file is empty we send the default values
if ($size <= 0){
@output[0] =":master";
$self->debugMsg(3,"No manifest string supplied, we assumed master branch by default.\n");
}
return @output;
}
############################################################
# replace_strings
#
# replace keywords in strings.
#
# Args:
# instring - string to scan
# map - a map of replacements
#
# Returns
# instring with keywords replaced
############################################################
sub replace_strings {
my ($self,$instring,$map) = @_;
foreach my $str (keys % {$map}) {
$instring =~ s/$str/$map->{$str}/g;
}
return $instring;
}
############################################################
# getChanges
#
# get the list of changes cached in a property
#
# Returns
# array of change records
############################################################
sub getChanges {
my ($self) = @_;
my @changes=();
my $cfg = new ElectricCommander::PropDB($self->getCmdr(),"");
my $change_str = $cfg->getProp("/myJob/gerrit_changes");
if (!defined $change_str || "$change_str" eq "") {
return @changes;
}
$self->debugMsg(2,"Changes:$change_str");
my $json = JSON->new->utf8;
my $ref = $json->decode($change_str);
return (@$ref);
}
#############################################################
# runCmd: run a command on the gerrit sshd connections
#
# cmdin - the command to run
# input - the text to pipe into cmd (optional)
#
# returns
# exitstatus - exit code of command
# text - stdout of command
#############################################################
sub runCmd {
my $self = shift;
my $cmd = shift;
my $input = shift;
$self->debugMsg(4,"entering runCmd...\n");
## for test, if canned output is given, pop off
## the next output block and return
if ($::gRunCmdUseFakeOutput) {
if ("$::gFakeCmdOutput" eq "") {
# we ran out of fake output
return (99,"no more output");
}
my @lines = split(/\|\|/, "$::gFakeCmdOutput");
my $text = shift (@lines);
my ($exitstatus,$out) = split(/\:\:/,$text);
chomp $exitstatus;
# push remaining text
my $newv = join ("\|\|", @lines);
$::gFakeCmdOutput = $newv;
return ($exitstatus,$out);
}
my $c = $self->ssh_connect(
$self->getServer(),
$self->getUser(),
$self->getPort(),
$self->getSSHPub,
$self->getSSHPvt,
);
$self->debugMsg(4,"runCmd:$cmd\ninput:$input\n");
my ($exit,$out) = $self->ssh_runCommand($c,$cmd,$input);
return ($exit,$out);
}
#############################################################
# runLocalCmd: run a command on the local machine
#
# cmdin - the command to run
# input - the text to pipe into cmd (optional)
#
# returns
# exitstatus - exit code of command
# text - stdout of command
#############################################################
sub runLocalCmd {
my $self = shift;
my $cmd = shift;
my $input = shift;
## for test, if canned output is given, pop off
## the next output block and return
if ($::gRunCmdUseFakeOutput) {
if ("$::gFakeCmdOutput" eq "") {
# we ran out of fake output
return (99,"no more output");
}
my @lines = split(/\|\|/, "$::gFakeCmdOutput");
my $text = shift (@lines);
my ($exitstatus,$out) = split(/\:\:/,$text);
chomp $exitstatus;
# push remaining text
my $newv = join ("\|\|", @lines);
$::gFakeCmdOutput = $newv;
return ($exitstatus,$out);
}
my $pid = open2 (\*CMD_OUT, \*CMD_IN, $cmd);
if (defined $input && "$input" ne "") {
print CMD_IN "$input\n";
}
close CMD_IN;
my $out = do { local $/; <CMD_OUT> };
close CMD_OUT;
waitpid $pid, 0;
my $exitstatus = $? >> 8;
return ($exitstatus,$out);
}
############################################################
# makeReplacementMap
#
# make a map out of all opts suitable for use in
# replacement calls (replaceStrings)
#
# Returns
# the hashmap
############################################################
sub makeReplacementMap {
my $self = shift;
my $opts = shift;
my $map = ();
foreach my $opt (keys % {$opts}) {
$map->{"{$opt}"} = "$opts->{$opt}";
}
return $map;
}
############################################################
# SCAN FUNCTIONS
############################################################
###################################################
# processNewChanges
#
# find new gerrit changes that this integration has not
# previously processed and process them
#
# args
# opts - configuration options
#
# returns
# nothing
###################################################
sub processNewChanges {
my $self = shift;
my $opts = shift;
my @project_branches;
if ($opts->{'use_file_manifest'} == 1) {
@project_branches = $self->parseManifest($opts->{'changes_manifest_file'});
} else {
@project_branches = $self->parseManifestStr($opts->{'changes_manifest_str'});
}
foreach $line (@project_branches){
@info = split /:/, $line;
my $size = scalar @info;
my $proj = "";
my $branch = "";
my $change_id = "";
if ($size == 2){
$proj = @info[0];
$branch = @info[1];
chomp $proj, $branch;
$opts->{"gerrit_project"} = $proj;
$opts->{"gerrit_branch"} = $branch;
$self->debugMsg(4, "processSingleProject=$proj|$branch");
$self->processSingleProject($opts);
}
if ( ($size == 3) || ($size == 1) ) {
$change_id = @info[0];
chomp $change_id;
if ($size == 3) {
$proj = @info[1];
$branch = @info[2];
$opts->{"gerrit_project"} = $proj;
$opts->{"gerrit_branch"} = $branch;
chomp $proj, $branch;
} else {
$opts->{"gerrit_project"} = "";
$opts->{"gerrit_branch"} = "";
}
$opts->{"gerrit_change_id"} = $change_id;
$self->debugMsg(4, "processSingleChanges=$change_id");
$self->processSingleChanges($opts);
}
}
}
###################################################
# processSingleProject
#
# find new gerrit changes that this integration has not
# previously processed and process them
#
# args
# opts - configuration options
#
# returns
# nothing
###################################################
sub processSingleProject{
my $self = shift;
my $opts = shift;
$self->showMsg("Processing new gerrit changes for project $opts->{gerrit_project}"
. " and branch $opts->{gerrit_branch}...");
# Get list of all open changes
my @ch = $self->getOpenChanges("$opts->{gerrit_project}", "$opts->{gerrit_branch}");
if (!@ch) {
$self->showMsg( "No changes found.");
return;
}
foreach my $row (@ch) {
my $changeid = $row->{columns}{change_id};
my $patchid = $row->{columns}{current_patch_set_id};
my $project = $row->{columns}{dest_project_name};
$self->showMsg( "Found change $changeid:$patchid");
# see if any of them need processing
my $uuid = 0;
my $state = "jobRunning";
if ($opts->{devbuild_mode} eq "auto") {
$state = "jobComplete";
$uuid += $self->testECState($changeid,$patchid,$state);
$state = "jobRunning";
$uuid += $self->testECState($changeid,$patchid,$state);
} else {
$state = "jobAvailable";
$uuid += $self->testECState($changeid,$patchid,$state);
}
if ($uuid) {
$self->debugMsg(1, "Already processed change=$changeid patchset=$patchid");
next;
}
$self->showMsg( "Processing change=$changeid patchset=$patchid");
# create a comment
my $msg = "";
if ($opts->{devbuild_mode} eq "auto") {
# run a job too
$self->showMsg ("Running job for $changeid:$patchid");
$msg = $self->launchECJob($opts,$changeid,$patchid,$project);
} else {
# just put a link in comment for building
$self->showMsg("Creating a link to run a job for $changeid:$patchid");
$msg = "This change can be built with ElectricCommander. "
. "https://$opts->{cmdr_webserver}/commander/link/runProcedure/projects/"
. uri_escape($opts->{devbuild_cmdr_project}) . "/procedures/"
. uri_escape($opts->{devbuild_cmdr_procedure}) . "?"
. "&numParameters=4"
. "¶meters1_name=gerrit_cfg"
. "¶meters1_value="
. uri_escape($opts->{gerrit_cfg})
. "¶meters2_name=changeid"
. "¶meters2_value=$changeid"
. "¶meters3_name=project"
. "¶meters3_value=$project"
. "¶meters4_name=patchid"
. "¶meters4_value=$patchid";
# DevBuildPrepare::annotate does this for the 'auto' Dev Build Mode.
# For manual mode, we set the comments here
$self->setECState($project,$changeid, $patchid, $state, $msg, "","");
}
}
}
###################################################
# processSingleChanges
#
#
#
#
# args
# opts - configuration options
#
# returns
# nothing
###################################################
sub processSingleChanges{
my $self = shift;
my $opts = shift;
my $single_change = 0;
my $using_int = 0;
if ( ($opts->{'gerrit_project'} ne "") && ($opts->{'gerrit_branch'} ne "") ) {
$self->showMsg("Processing change: $opts->{'gerrit_change_id'} from project : $opts->{'gerrit_project'} branch: $opts->{'gerrit_branch'} ");
} else {
$self->showMsg("Processing change: $opts->{'gerrit_change_id'}");
$single_change = 1;
}
$using_int = $self->is_int($opts->{'gerrit_change_id'});
my @ch;
my $query = "";
if ($using_int == 1) {
$query = "SELECT * FROM " . $self->t('CHANGES') . " WHERE CHANGE_ID = '". $opts->{'gerrit_change_id'} ."';";
} else {
$query = "SELECT * FROM " . $self->t('CHANGES') . " WHERE CHANGE_KEY = '". $opts->{'gerrit_change_id'} ."';";
}
@ch = $self->gerrit_db_query($query);
my $row = @ch[0];
my $change_open = $row->{columns}{open};
my $changeid = $row->{columns}{change_id};
my $patchid = $row->{columns}{current_patch_set_id};
my $project = $row->{columns}{dest_project_name};
if ($change_open eq 'Y'){
$self->showMsg( "Change $changeid:$patchid");
# see if any of them need processing
my $uuid = 0;
my $state = "jobRunning";
if ($opts->{devbuild_mode} eq "auto") {
$state = "jobComplete";
$uuid += $self->testECState($changeid,$patchid,$state);
$state = "jobRunning";
$uuid += $self->testECState($changeid,$patchid,$state);
} else {
$state = "jobAvailable";
$uuid += $self->testECState($changeid,$patchid,$state);
}
if ($uuid) {
$self->debugMsg(1, "Already processed change=$changeid patchset=$patchid");
next;
}
$self->showMsg( "Processing change=$changeid patchset=$patchid");
# create a comment
my $msg = "";
if ($opts->{devbuild_mode} eq "auto") {
# run a job too
$self->showMsg ("Running job for $changeid:$patchid");
$msg = $self->launchECJob($opts,$changeid,$patchid,$project);
} else {
# just put a link in comment for building
$self->showMsg("Creating a link to run a job for $changeid:$patchid");
$msg = "This change can be built with ElectricCommander. "
. "https://$opts->{cmdr_webserver}/commander/link/runProcedure/projects/"
. uri_escape($opts->{devbuild_cmdr_project}) . "/procedures/"
. uri_escape($opts->{devbuild_cmdr_procedure}) . "?"
. "&numParameters=4"
. "¶meters1_name=gerrit_cfg"
. "¶meters1_value="
. uri_escape($opts->{gerrit_cfg})
. "¶meters2_name=changeid"
. "¶meters2_value=$changeid"
. "¶meters3_name=project"
. "¶meters3_value=$project"
. "¶meters4_name=patchid"
. "¶meters4_value=$patchid";
$self->setECState($project,$changeid, $patchid, $state, $msg, "","");
}
}else {
if (defined $changeid) {
$self->showMsg("The change: $changeid is closed");
} else {
$self->showMsg("The change: $opts->{'gerrit_change_id'} cannot be found.");
}
}
}
###################################################
# launchECJob
#
# Launch a new EC job to test these changes
#
# args
# opts - configuration options
# changeid - change id of changes
# patchid - patchid of changes
#
# returns
# msg - message to put in gerrit comment
###################################################
sub launchECJob {
my $self = shift;
my $opts = shift;
my $changeid = shift;
my $patchid = shift;
my $project = shift;
my $xPath = $self->getCmdr()->runProcedure($opts->{devbuild_cmdr_project} ,
{ procedureName => $opts->{devbuild_cmdr_procedure},
actualParameter => [
{actualParameterName => 'changeid', value => "$changeid" },
{actualParameterName => 'patchid', value => "$patchid" },
{actualParameterName => 'project', value => "$project" },
{actualParameterName => 'gerrit_cfg', value => "$opts->{gerrit_cfg}" },
]
});
my $msg = "";
my $errcode = $xPath->findvalue('//responses/error/code')->string_value;
if (defined $errcode && "$errcode" ne "") {
my $errmsg = $xPath->findvalue('//responses/error/message')->string_value;
$msg = "ElectricCommander tried but could not run a job for this change. [$errcode]";
} else {
my $jobId = $xPath->findvalue('//responses/response/jobId')->string_value;
# Mark the change as processed
$msg = "This change is being built with ElectricCommander. "
. "https://$opts->{cmdr_webserver}/commander/link/jobDetails/jobs/$jobId";
}
return $msg;
}
###################################################
# processFinishedJobs
#
# find jobs that were started by this integration
# and if complete, mark them in gerrit comments
#
# args
# opts - configuration options
#
# returns
# nothing
###################################################
sub processFinishedJobs {
my $self = shift;
my $opts = shift;
$self->showMsg("Processing finished jobs...");
if (!defined $opts) {
$self->showError("bad arguments to processFinishedJobs");
return;
}
my @filter,@selects;
push (@filter, {"propertyName" => "status",
"operator" => "equals",
"operand1" => "completed"});
push (@filter, {"propertyName" => "projectName",
"operator" => "equals",
"operand1" => $opts->{devbuild_cmdr_project}});
push (@filter, {"propertyName" => "procedureName",
"operator" => "equals",
"operand1" => $opts->{devbuild_cmdr_procedure}});
push (@filter, {"propertyName" => "processed_by_gerrit",
"operator" => "notEqual",
"operand1" => "done"});
push (@selects, {"propertyName" => "outcome"});
push (@selects, {"propertyName" => "branch"});
push (@selects, {"propertyName" => "changeid"});
push (@selects, {"propertyName" => "patchid"});
push (@selects, {"propertyName" => "project"});
push (@selects, {"propertyName" => "gerrit_cfg"});
# get list of jobs that are finished but not recorded
# this should be a relatively small list
# only returns objectId's
my $xPath = $self->getCmdr()->findObjects("job", {numObjects => "0",
filter => \@filter, select => \@selects});
{
my $errcode = $xPath->findvalue('//responses/error/code')->string_value;
if (defined $errcode && "$errcode" ne "") {
my $errmsg = $xPath->findvalue('//responses/error/message')->string_value;
$self->showError("error [$errcode] when searching jobs. $errmsg");
return;
}
}
# for each job found
my $objectNodeset = $xPath->find('//response/objectId');
foreach my $node ($objectNodeset->get_nodelist)
{
my $objectId = $node->string_value();
# get the details
my $jPath = $self->getCmdr()->getObjects({objectId => $objectId, select => \@selects});
{
my $errcode = $jPath->findvalue('//responses/error/code')->string_value;
if (defined $errcode && "$errcode" ne "") {
my $errmsg = $jPath->findvalue('//responses/error/message')->string_value;
$self->showError("error [$errcode] when looking up object #$objectid. $errmsg");
next;
}
}
# load up all the properties found
my $props;
my $on = $jPath->find('//responses/response/object/property');
foreach my $n ($on->get_nodelist) {
my $name= $n->findvalue('propertyName')->string_value;
my $value= $n->findvalue('value')->string_value;
$props->{$name} = "$value";
$self->debugMsg(1, "props{$name}=$props->{$name}");
}
my $jobId= $jPath->findvalue('//jobId')->string_value;
my $outcome= $jPath->findvalue('//outcome')->string_value;
$self->showMsg("Found job $jobId for"
. " change=$props->{changeid} patchset=$props->{patchid}"
. " completed with outcome $outcome");
# mark as done
$self->getCmdr()->setProperty("/jobs/$jobId/processed_by_gerrit","done");
# sanity check this job
if (!defined $props->{changeid} || $props->{changeid} eq "" ||
!($props->{changeid} =~ /^(\d+\.?\d*|\.\d+)$/) ) {
$self->debugMsg(1, "changeid[$props->{changeid}] for job $jobId is invalid");
next;
}
# get rules from config
my $cfg = new ElectricCommander::PropDB($self->getCmdr(),"/myProject/gerrit_cfgs");
my $rules = $cfg->getCol($props->{gerrit_cfg},"dev_build_rules");
my ($filters, $actions) = $self->parseRules("$rules");
my $cat = "";
my $value = "";
if ($outcome eq "success") {
$cat = $actions->{SUCCESS}{CAT} || "";
$value = $actions->{SUCCESS}{VAL} || "";
$msg = "This change was successfully built with ElectricCommander. "
. "https://$opts->{cmdr_webserver}/commander/link/jobDetails/jobs/$jobId";
} else {
$cat = $actions->{ERROR}{CAT} || "";
$value = $actions->{ERROR}{VAL} || "";
$msg = "This change failed the ElectricCommander build. "
. "https://$opts->{cmdr_webserver}/commander/link/jobDetails/jobs/$jobId";
}
$self->setECState("$props->{project}","$props->{changeid}",
"$props->{patchid}","jobComplete", $msg, $cat, $value);
}
return;
}
###################################################
# cleanup
#
# remove previous runs of the scanner job
#
# args
# opts - configuration options
#
# returns
# nothing
###################################################
sub cleanup {
my $self = shift;
# Check for the OS Type
my $osIsWindows = $^O =~ /MSWin/;
my $cfg = new ElectricCommander::PropDB($self->getCmdr(),"");
my $projectName = $cfg->getProp("/plugins/EC-Gerrit/projectName");
my $procedureName = "DeveloperScan";
my $scheduleName = "Gerrit New Change Scanner";
# Find all previous runs of this job
my @filterList;
push (@filterList, {"propertyName" => "projectName",
"operator" => "equals",
"operand1" => "$projectName"});
push (@filterList, {"propertyName" => "procedureName",
"operator" => "equals",
"operand1" => "$procedureName"});
push (@filterList, {"propertyName" => "status",
"operator" => "equals",
"operand1" => "completed"});
# Delete only the jobs that this SCHEDULE started (unless deleteAll specified)
push (@filterList, {"propertyName" => "scheduleName",
"operator" => "equals",
"operand1" => "$scheduleName"});
push (@filterList, {"propertyName" => "outcome",
"operator" => "notEqual",
"operand1" => "error"});
# Run the Query
my $xPath = $self->getCmdr()->findObjects(
"job", {numObjects => "500", filter => \@filterList });
# Loop over all returned jobs
my $nodeset = $xPath->find('//job');
foreach my $node ($nodeset->get_nodelist)
{
# Find the workspaces (there can be more than one if some steps
# were configured to use a different workspace
my $jobId = $xPath->findvalue('jobId', $node);
my $jobName = $xPath->findvalue('jobName', $node);
my $xPath = $self->getCmdr()->getJobInfo($jobId);
my $wsNodeset = $xPath->find('//job/workspace');
foreach my $wsNode ($wsNodeset->get_nodelist) {
my $workspace;
if ($osIsWindows)
{
$workspace = $xPath->findvalue('./winUNC', $wsNode);
$workspace =~ s/\/\//\\\\/g;
}
else
{
$workspace = $xPath->findvalue('./unix', $wsNode);
}
# Delete the workspace (after checking its name as a sanity test)
# look for "job_nnn" or "ElectricSentry-nnn"
if ($workspace =~ /[-_][\d]+$/)
{
use File::Path;
rmtree ([$workspace]) ;
$self->showMsg( "Deleted workspace - $workspace");
}
}
# Delete the job
my $xPath = $self->getCmdr()->deleteJob($jobId);
$self->showMsg( "Deleted job - $jobName");
}
}
###############################################
# error routines
###############################################
###############################################
# showError
#
# print an error and quit
#
# args
# msg - the message to show
# code - if present, exit with this code
#
###############################################
sub showError {
my $self = shift;
my $msg = shift;
my $code = shift;
print STDERR "Error: $msg\n";
if (defined $code) {
exit $code;
}
}
###############################################
# showMsg
#
# print a message
#
# args
# msg - the message to show
#
###############################################
sub showMsg {
my $self = shift;
my $msg = shift;
print "$msg\n";
}
###############################################
# debugMsg
#
# print a message if debug level permits
#
# args
# lvl - the debug level for this message
# msg - the message to show
#
###############################################
sub debugMsg {
my $self = shift;
my $lvl = shift;
my $msg = shift;
if ($self->getDbg() >= $lvl) {
print "$msg\n";
}
}
###############################################
# Debugging routines
###############################################
###############################################
# printAllTables
#
# enumerates all tables in schema, loads them
# into perl hashes and prints contents
#
# could result in very large datasets
# should only be used in development
# on small gerrit dbs.
# This sub-routine is not supported in production and
# may only be used in development with either
# H2 or MySql databases.
###############################################
sub printAllTables {
my $self = shift;
my @tables = $self->gerrit_db_query("\\d");
$self->print_table(@tables);
my $rows = scalar(@tables);
for (my $index=0; $index < $rows; $index++) {
my @tbl = $self->gerrit_db_query("select * from " .
$self->t($tables[$index]->{columns}{table_name}) . ";");
$self->print_table(@tbl);
}
}
##########################################
# print_table
# print the results of a query
#
# args
# array returned from gerrit_db_query
#
# returns
# nothing
##########################################
sub print_table {
my ($self,@table) = @_;
print "========table =========\n";
my $row=0;
foreach my $row (@table) {
foreach my $col (keys % {$row}) {
print "row[$row]->{$col}=$row->{$col}\n";
}
$row++;
}
}
############################################################
# print_filters
#
# For debugging, prints out a filters map
#
# Args:
# filters - a filters map
#
# Returns
# prints out contents of filters map
############################################################
sub print_filters {
my ($self,$filters) = @_;
# for each filter
print "--FILTERS--\n";
foreach my $num (sort keys % {$filters}) {
print "filter $num: type=$filters->{$num}{TYPE}"
. " cat=$filters->{$num}{CAT}"
. " op=$filters->{$num}{OP}"
. " num=$filters->{$num}{VAL}"
. " user_op=$filters->{$num}{USER_OP}"
. " user=$filters->{$num}{USER} \n";
}
}
############################################################
# print_actions
#
# For debugging, prints out a actions map
#
# Args:
# actions - a actions map
#
# Returns
# prints out contents of actions map
############################################################
sub print_actions {
my ($self,$actions) = @_;
print "--ACTIONS--\n";
print "action SUCCESS "
. " $actions->{SUCCESS}{CAT}"
. " $actions->{SUCCESS}{USER}\n";
print "action ERROR "
. " $actions->{ERROR}{CAT}"
. " $actions->{ERROR}{USER}\n";
}
############################################################
# print_metrics
#
# For debugging, prints out a metrics map
#
# Args:
# metrics - a metrics map
#
# Returns
# prints out contents of metrics map
############################################################
sub print_metrics {
my ($self,$metrics) = @_;
# for each user
print "--METRICS--\n";
foreach my $changeid (keys % {$metrics}) {
print "---change $changeid ---\n";
foreach my $user (sort keys % {$metrics->{$changeid}}) {
foreach my $cat (sort keys %{$metrics->{$changeid}{$user}}) {
print "metric: user=$user category=$cat"
. " min=$metrics->{$changeid}{$user}{$cat}{MIN}"
. " max=$metrics->{$changeid}{$user}{$cat}{MAX}"
. " count=$metrics->{$changeid}{$user}{$cat}{COUNT}\n";
}
}
}
}
############################################################
# print_changes
#
# For debugging, prints out a changes array
#
# Args:
# changes - a changes array
#
# Returns
# prints out contents of changes array
############################################################
sub print_changes {
my ($self,@changes) = @_;
# for each user
print "--CHANGES--\n";
foreach my $change (@changes) {
print "Change " . $change->{columns}{change_id} . "\n";
}
}
############################################################
# print_eligible
#
# For debugging, prints out a eligible array
#
# Args:
# eligible - a eligible map
#
# Returns
# prints out contents of eligible array
############################################################
sub print_eligible {
my ($self,@eligible) = @_;
# for each change
print "--ELIGIBLE LIST--\n";
foreach my $changestr (@eligible) {
my ($c,$patch,$proj) = split(/:/,$changestr);
print "$c:$patch:$proj\n";
}
}
############################################################
# print_idmap
#
# For debugging, prints out a idmap map
#
# Args:
# eligible - a idmap map
#
# Returns
# prints out contents of patchid map
############################################################
sub print_idmap {
my ($self,$idmap) = @_;
# for each change
print "--PATCH SET IDS--\n";
foreach my $changeid (keys % {$idmap}) {
print "$changeid:$idmap->{$changeid}{patchid}:$idmap->{$changeid}{project}\n";
}
}
####################### SSH Operation Implementations #########################
# ------------------------------------------------------------------------
# ssh_getDefaultTargetPort
#
# Returns the default target port for this protocol.
#
# Arguments:
# None
# ------------------------------------------------------------------------
sub ssh_getDefaultTargetPort() {
return 29418;
}
# ------------------------------------------------------------------------
# ssh_connect
#
# Opens a connection to the proxy target via ssh.
#
# Arguments:
# host - Name or IP address of the proxy target.
# port - (optional) Port to connect to. Defaults to 22.
# ------------------------------------------------------------------------
sub ssh_connect {
my ($self,$host, $userName, $port, $pubKeyFile, $privKeyFile) = @_;
# Be sure that pubKeyFile, and privKeyFile are defined and that the two
# files actually exist. Error out otherwise.
$pubKeyFile || die "ssh_connect: Public key file must be specified; use " .
"setSSHKeyFiles\n";
if (! -r $pubKeyFile) {
die "ssh_connect: Public key file '$pubKeyFile' does not exist or " .
"is not readable\n";
}
$privKeyFile || die "ssh_connect: Private key file must be specified; " .
"use setSSHKeyFiles\n";
if (! -r $privKeyFile) {
die "ssh_connect: Private key file '$privKeyFile' does not exist " .
"or is not readable\n";
}
# Ok, try and connect...
my $ssh2 = Net::SSH2->new();
my $result = eval {
$ssh2->connect($host, $port);
};
if (!$result) {
die "ssh_connect: Error connecting to $host:$port: $!\n";
}
if ($self->getDbg > 4) {
$ssh2->debug(1);
}
$self->debugMsg(5,"ssh_connect: Creating session : Connecting to " .
"$host:$port with userName=$userName pubKeyFile=$pubKeyFile " .
"privKeyFile=$privKeyFile");
# libssh2 has a bug where sometimes key-authentication fails even
# though the keyfiles are perfectly valid. Retry upto three more times
# with a little sleep in between before giving up.
my $attemptCount = 1;
my $maxAttempts = 4;
my $errorString;
for (; $attemptCount <= $maxAttempts &&
!$ssh2->auth_publickey($userName, $pubKeyFile, $privKeyFile);
$attemptCount++) {
$errorString = ($ssh2->error())[2];
$self->debugMsg(5,"Authentication attempt $attemptCount failed with error: " .
"$errorString");
sleep 2;
}
if ($attemptCount == $maxAttempts+1) {
my $msg =
"ssh_connect: Key authentication failed for $userName using " .
"the following key files:\n" .
"public key file: $pubKeyFile\n" .
"private key file: $privKeyFile\n" .
"error: $errorString";
$self->showError(4,$msg);
}
# Success! Save off the session handle.
my $context = $ssh2;
$self->debugMsg(5,"ssh_connect: Connection succeeded!");
return $context;
}
# ------------------------------------------------------------------------
# ssh_runCommand
#
# Runs the given command-line on the proxy target and streams the
# result to stdout.
#
# Arguments:
# context - Context object that contains connection info.
# cmdLine - command-line to execute.
# ------------------------------------------------------------------------
sub ssh_runCommand {
my ($self,$context, $cmdLine,$input) = @_;
my $channel = $context->channel();
$channel->blocking(0);
$channel->ext_data('merge');
$channel->exec($cmdLine);
$channel->write($input);
my $out = "";
my $buf;
while (!$channel->eof()) {
if (defined($channel->read($buf, 4096))) {
$out .= $buf;
} else {
# We got no data; try again in a second.
sleep 1;
}
}
return ($channel->exit_status(),$out);
}
####################################################################
# dumpOpts
#
####################################################################
sub dumpOpts{
my ($self, $opts) = @_;
print "\n-------------start opts------------\n";
foreach my $e (keys % {$opts}) {
print " key=$e, val=$opts->{$e}\n";
}
print "\n-------------end opts------------\n";
}
#####################################################################
# is_int
# Determines if an scalar contains only digits not float of strings
###################################################################
sub is_int{
my $self = shift;
my $string = shift;
if ($string =~ /^\d+$/) {
return 1;
} else {
return 0;
}
}
####################################################################
# t
# Is used to convert a table name form uppercase to lowercase
# according to a global flag
###################################################################
sub t {
my ($self, $name) = @_;
if (!$::gTableCase) {
my $useUpper = $self->getCmdr()->getPropertyValue("/myProject/use_upper_case_table_names");
if ($useUpper) {
$::gTableCase = "upper";
} else {
$::gTableCase = "lower";
}
}
if ($::gTableCase eq "lower") {
return lc($name);
}elsif ($::gTableCase eq "upper") {
return uc($name);
}
}
1;
| electric-cloud/EC-Gerrit | src/main/resources/project/server/ECGerrit.pm | Perl | apache-2.0 | 68,867 |
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2020] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
package XrefParser::VBPubMedParser;
use strict;
use warnings;
use Carp;
use POSIX qw(strftime);
use File::Basename;
use base qw( XrefParser::BaseParser );
# Parse the external description file
#
#PubMed ID Stable ID Feature Gene_ID (?) Origin
#1354853 AAEL009742 gene AAEL009742 Inferred from UniProt entry ABDA_AEDAE (P29552)
#1961751 AAEL006563 gene AAEL006563 Inferred from UniProt entry VCP_AEDAE (P42660)
#2052024 AAEL006424 gene AAEL006424 Inferred from UniProt entry ALL2_AEDAE (P18153)
sub run {
my ( $self, $ref_arg ) = @_;
my $source_id = $ref_arg->{source_id};
my $species_id = $ref_arg->{species_id};
my $files = $ref_arg->{files};
my $verbose = $ref_arg->{verbose};
if ( ( !defined $source_id ) or ( !defined $species_id ) or ( !defined $files ) ) {
croak "Need to pass source_id, species_id and files as pairs";
}
$verbose |= 0;
my $file = @{$files}[0];
print "source_id = $source_id, species= $species_id, file = $file\n" if $verbose;
my $added = 0;
my $count = 0;
my $file_io = $self->get_filehandle($file);
if ( !defined $file_io ) {
print STDERR "ERROR: Could not open file $file\n";
return 1;
}
while ( my $line = $file_io->getline() ) {
if ( $line !~ /^#/ ) {
chomp $line;
my ( $PubMed_id, $gene_id, $rien, $name, $origin ) = split "\t", $line; #and use the gene_id as accession
my $descr_full = "PubMed ID $PubMed_id - $origin";
#print STDERR "PMID: $PubMed_id, GID: $gene_id, NONE: $rien, NOM: $name, ORI: $origin\n" ;
my $xref_id = $self->get_xref( $gene_id, $source_id, $species_id );
if ( !defined($xref_id) ) {
$xref_id = $self->add_xref(
{
acc => $PubMed_id,
label => $PubMed_id,
desc => $descr_full,
source_id => $source_id,
species_id => $species_id,
info_type => 'DIRECT'
}
);
$count++;
}
if ( defined($gene_id) and $gene_id ne '-' ) {
$self->add_direct_xref( $xref_id, $gene_id, 'Gene', '' );
$added++;
}
}
}
$file_io->close();
print "Added $count xrefs and $added Direct xrefs to genes for VBPubMed\n" if $verbose;
return 0;
}
1;
| james-monkeyshines/ensembl | misc-scripts/xref_mapping/XrefParser/VBPubMedParser.pm | Perl | apache-2.0 | 3,233 |
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2021] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
package EnsEMBL::Web::TextSequence::View;
use strict;
use warnings;
use File::Basename;
use JSON qw(encode_json);
use List::Util qw(max);
use List::MoreUtils qw(any firstidx);
use EnsEMBL::Web::PureHub;
use EnsEMBL::Web::TextSequence::Sequence;
use EnsEMBL::Web::TextSequence::Output::Web;
use EnsEMBL::Web::TextSequence::Legend;
use EnsEMBL::Web::TextSequence::ClassToStyle::CSS;
use EnsEMBL::Web::TextSequence::SequenceSet;
# A view is comprised of one or more interleaved sequences.
sub new {
my ($proto,$hub) = @_;
my $class = ref($proto) || $proto;
my $self = {
hub => $hub,
output => undef,
legend => undef,
phase => 0,
sequenceset => undef,
};
bless $self,$class;
$self->output(EnsEMBL::Web::TextSequence::Output::Web->new);
$self->reset;
return $self;
}
# XXX should probably be in SequenceSet, but for that we need custom
# SequenceSets.
sub make_sequence { # For IoC: override me if you want to
my ($self,$set) = @_;
return EnsEMBL::Web::TextSequence::Sequence->new($self,$set);
}
# XXX deprecate
sub reset {
my ($self) = @_;
$self->{'sequenceset'} = EnsEMBL::Web::TextSequence::SequenceSet->new($self);
$self->output->reset;
}
sub phase { $_[0]->{'phase'} = $_[1] if @_>1; return $_[0]->{'phase'}; }
sub interleaved { return 1; }
sub output {
my ($self,$output) = @_;
if(@_>1) {
$self->{'output'} = $output;
$output->view($self);
}
return $self->{'output'};
}
sub make_legend { # For IoC: override me if you want to
return EnsEMBL::Web::TextSequence::Legend->new(@_);
}
sub legend {
my ($self) = @_;
$self->{'legend'} ||= $self->make_legend;
return $self->{'legend'};
}
# XXX into subclasses
sub set_annotations {
my ($self,$config) = @_;
$self->add_annotation(EnsEMBL::Web::TextSequence::Annotation::Sequence->new);
$self->add_annotation(EnsEMBL::Web::TextSequence::Annotation::Alignments->new) if $config->{'align'};
$self->add_annotation(EnsEMBL::Web::TextSequence::Annotation::Variations->new([0,2])) if $config->{'snp_display'} && $config->{'snp_display'} ne 'off';
$self->add_annotation(EnsEMBL::Web::TextSequence::Annotation::Exons->new) if ($config->{'exon_display'}||'off') ne 'off';
$self->add_annotation(EnsEMBL::Web::TextSequence::Annotation::Codons->new) if $config->{'codons_display'};
}
sub set_markup {}
sub new_sequence {
my ($self,$position) = @_;
return $self->{'sequenceset'}->new_sequence($position);
}
sub sequences { return $_[0]->{'sequenceset'}->sequences; }
sub root_sequences { return $_[0]->{'sequenceset'}->root_sequences; }
sub slices { my $self = shift; return $self->{'sequenceset'}->slices(@_); }
# Only to be called by line
sub _new_line_num { return $_[0]->{'sequenceset'}->_new_line_num; }
sub _hub { return $_[0]->{'hub'}; }
sub width { $_[0]->{'width'} = $_[1] if @_>1; return $_[0]->{'width'}; }
sub add_annotation {
my $self = shift;
return $self->{'sequenceset'}->add_annotation(@_);
}
# XXX should all be in annotation: markup is too late
sub add_markup {
my $self = shift;
return $self->{'sequenceset'}->add_markup(@_);
}
sub prepare_ropes {
my $self = shift;
return $self->{'sequenceset'}->prepare_ropes(@_);
}
sub annotate {
my $self = shift;
return $self->{'sequenceset'}->annotate(@_);
}
sub markup {
my $self = shift;
return $self->{'sequenceset'}->markup(@_);
}
sub transfer_data {
my $self = shift;
return $self->{'sequenceset'}->transfer_data(@_);
}
sub transfer_data_new {
my $self = shift;
return $self->{'sequenceset'}->transfer_data_new(@_);
}
sub style_files {
my ($name,$path) = fileparse(__FILE__);
$path .= "/seq-styles.yaml";
return [$path];
}
1;
| Ensembl/ensembl-webcode | modules/EnsEMBL/Web/TextSequence/View.pm | Perl | apache-2.0 | 4,393 |
#
# Copyright 2018 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package cloud::docker::restapi::mode::containerusage;
use base qw(centreon::plugins::templates::counter);
use strict;
use warnings;
use Digest::MD5 qw(md5_hex);
my $instance_mode;
sub custom_status_threshold {
my ($self, %options) = @_;
my $status = 'ok';
my $message;
eval {
local $SIG{__WARN__} = sub { $message = $_[0]; };
local $SIG{__DIE__} = sub { $message = $_[0]; };
if (defined($instance_mode->{option_results}->{critical_container_status}) && $instance_mode->{option_results}->{critical_container_status} ne '' &&
eval "$instance_mode->{option_results}->{critical_container_status}") {
$status = 'critical';
} elsif (defined($instance_mode->{option_results}->{warning_container_status}) && $instance_mode->{option_results}->{warning_container_status} ne '' &&
eval "$instance_mode->{option_results}->{warning_container_status}") {
$status = 'warning';
}
};
if (defined($message)) {
$self->{output}->output_add(long_msg => 'filter status issue: ' . $message);
}
return $status;
}
sub custom_status_output {
my ($self, %options) = @_;
my $msg = 'state : ' . $self->{result_values}->{state};
return $msg;
}
sub custom_status_calc {
my ($self, %options) = @_;
$self->{result_values}->{state} = $options{new_datas}->{$self->{instance} . '_state'};
$self->{result_values}->{name} = $options{new_datas}->{$self->{instance} . '_name'};
return 0;
}
sub custom_cpu_calc {
my ($self, %options) = @_;
my $delta_cpu_total = $options{new_datas}->{$self->{instance} . '_cpu_total_usage'} - $options{old_datas}->{$self->{instance} . '_cpu_total_usage'};
my $delta_cpu_system = $options{new_datas}->{$self->{instance} . '_cpu_system_usage'} - $options{old_datas}->{$self->{instance} . '_cpu_system_usage'};
$self->{result_values}->{prct_cpu} = (($delta_cpu_total / $delta_cpu_system) * $options{new_datas}->{$self->{instance} . '_cpu_number'}) * 100;
$self->{result_values}->{display} = $options{new_datas}->{$self->{instance} . '_display'};
return 0;
}
sub custom_memory_perfdata {
my ($self, %options) = @_;
my $extra_label = '';
if (!defined($options{extra_instance}) || $options{extra_instance} != 0) {
$extra_label .= '_' . $self->{result_values}->{display};
}
$self->{output}->perfdata_add(label => 'memory_used' . $extra_label, unit => 'B',
value => $self->{result_values}->{used},
warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning-' . $self->{label}, total => $self->{result_values}->{total}, cast_int => 1),
critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical-' . $self->{label}, total => $self->{result_values}->{total}, cast_int => 1),
min => 0, max => $self->{result_values}->{total});
}
sub custom_memory_threshold {
my ($self, %options) = @_;
my $exit = $self->{perfdata}->threshold_check(value => $self->{result_values}->{prct_used}, threshold => [ { label => 'critical-' . $self->{label}, exit_litteral => 'critical' }, { label => 'warning-' . $self->{label}, exit_litteral => 'warning' } ]);
return $exit;
}
sub custom_memory_output {
my ($self, %options) = @_;
my ($total_size_value, $total_size_unit) = $self->{perfdata}->change_bytes(value => $self->{result_values}->{total});
my ($total_used_value, $total_used_unit) = $self->{perfdata}->change_bytes(value => $self->{result_values}->{used});
my ($total_free_value, $total_free_unit) = $self->{perfdata}->change_bytes(value => $self->{result_values}->{free});
my $msg = sprintf("Memory Total: %s Used: %s (%.2f%%) Free: %s (%.2f%%)",
$total_size_value . " " . $total_size_unit,
$total_used_value . " " . $total_used_unit, $self->{result_values}->{prct_used},
$total_free_value . " " . $total_free_unit, $self->{result_values}->{prct_free});
return $msg;
}
sub custom_memory_calc {
my ($self, %options) = @_;
$self->{result_values}->{display} = $options{new_datas}->{$self->{instance} . '_display'};
$self->{result_values}->{total} = $options{new_datas}->{$self->{instance} . '_memory_total'};
$self->{result_values}->{used} = $options{new_datas}->{$self->{instance} . '_memory_usage'};
$self->{result_values}->{free} = $self->{result_values}->{total} - $self->{result_values}->{used};
$self->{result_values}->{prct_free} = $self->{result_values}->{free} * 100 / $self->{result_values}->{total};
$self->{result_values}->{prct_used} = $self->{result_values}->{used} * 100 / $self->{result_values}->{total};
return 0;
}
sub set_counters {
my ($self, %options) = @_;
$self->{maps_counters_type} = [
{ name => 'containers', type => 1, cb_prefix_output => 'prefix_containers_output', message_multiple => 'All containers are ok', skipped_code => { -11 => 1 } },
{ name => 'containers_traffic', type => 1, cb_prefix_output => 'prefix_containers_traffic_output', message_multiple => 'All container traffics are ok', skipped_code => { -11 => 1 } },
];
$self->{maps_counters}->{containers} = [
{ label => 'container-status', threshold => 0, set => {
key_values => [ { name => 'state' }, { name => 'name' } ],
closure_custom_calc => $self->can('custom_status_calc'),
closure_custom_output => $self->can('custom_status_output'),
closure_custom_perfdata => sub { return 0; },
closure_custom_threshold_check => $self->can('custom_status_threshold'),
}
},
{ label => 'cpu', set => {
key_values => [ { name => 'cpu_total_usage', diff => 1 }, { name => 'cpu_system_usage', diff => 1 }, { name => 'cpu_number' }, { name => 'display' } ],
output_template => 'CPU Usage : %.2f %%',
closure_custom_calc => $self->can('custom_cpu_calc'),
output_use => 'prct_cpu', threshold_use => 'prct_cpu',
perfdatas => [
{ label => 'cpu', value => 'prct_cpu', template => '%.2f',
unit => '%', min => 0, max => 100, label_extra_instance => 1, instance_use => 'display' },
],
}
},
{ label => 'memory', set => {
key_values => [ { name => 'memory_usage' }, { name => 'memory_total' }, { name => 'display' } ],
closure_custom_calc => $self->can('custom_memory_calc'),
closure_custom_output => $self->can('custom_memory_output'),
closure_custom_perfdata => $self->can('custom_memory_perfdata'),
closure_custom_threshold_check => $self->can('custom_memory_threshold'),
}
},
{ label => 'read-iops', set => {
key_values => [ { name => 'read_io', diff => 1 }, { name => 'display' } ],
per_second => 1,
output_template => 'Read IOPs : %.2f', output_error_template => "Read IOPs : %s",
perfdatas => [
{ label => 'read_iops', value => 'read_io_per_second', template => '%.2f',
unit => 'iops', min => 0, label_extra_instance => 1, instance_use => 'display_absolute' },
],
}
},
{ label => 'write-iops', set => {
key_values => [ { name => 'write_io', diff => 1 }, { name => 'display' } ],
per_second => 1,
output_template => 'Write IOPs : %.2f', output_error_template => "Write IOPs : %s",
perfdatas => [
{ label => 'write_iops', value => 'write_io_per_second', template => '%.2f',
unit => 'iops', min => 0, label_extra_instance => 1, instance_use => 'display_absolute' },
],
}
},
];
$self->{maps_counters}->{containers_traffic} = [
{ label => 'traffic-in', set => {
key_values => [ { name => 'traffic_in', diff => 1 }, { name => 'display' } ],
per_second => 1, output_change_bytes => 2,
output_template => 'Traffic In : %s %s/s',
perfdatas => [
{ label => 'traffic_in', value => 'traffic_in_per_second', template => '%.2f',
min => 0, unit => 'b/s', label_extra_instance => 1, instance_use => 'display_absolute' },
],
}
},
{ label => 'traffic-out', set => {
key_values => [ { name => 'traffic_out', diff => 1 }, { name => 'display' } ],
per_second => 1, output_change_bytes => 2,
output_template => 'Traffic Out : %s %s/s',
perfdatas => [
{ label => 'traffic_out', value => 'traffic_out_per_second', template => '%.2f',
min => 0, unit => 'b/s', label_extra_instance => 1, instance_use => 'display_absolute' },
],
}
},
];
}
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options, statefile => 1);
bless $self, $class;
$self->{version} = '1.0';
$options{options}->add_options(arguments =>
{
"container-id:s" => { name => 'container_id' },
"container-name:s" => { name => 'container_name' },
"filter-name:s" => { name => 'filter_name' },
"use-name" => { name => 'use_name' },
"warning-container-status:s" => { name => 'warning_container_status', default => '' },
"critical-container-status:s" => { name => 'critical_container_status', default => '' },
});
$self->{statefile_cache_containers} = centreon::plugins::statefile->new(%options);
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::check_options(%options);
$instance_mode = $self;
$self->change_macros();
$self->{statefile_cache_containers}->check_options(%options);
}
sub prefix_containers_traffic_output {
my ($self, %options) = @_;
return "Container '" . $options{instance_value}->{display} . "' ";
}
sub prefix_containers_output {
my ($self, %options) = @_;
return "Container '" . $options{instance_value}->{display} . "' ";
}
sub change_macros {
my ($self, %options) = @_;
foreach (('warning_container_status', 'critical_container_status')) {
if (defined($self->{option_results}->{$_})) {
$self->{option_results}->{$_} =~ s/%\{(.*?)\}/\$self->{result_values}->{$1}/g;
}
}
}
sub manage_selection {
my ($self, %options) = @_;
$self->{containers} = {};
$self->{containers_traffic} = {};
my $result = $options{custom}->api_get_containers(container_id => $self->{option_results}->{container_id},
container_name => $self->{option_results}->{container_name}, statefile => $self->{statefile_cache_containers});
foreach my $container_id (keys %{$result}) {
next if (!defined($result->{$container_id}->{Stats}));
my $name = $result->{$container_id}->{Name};
if (defined($self->{option_results}->{filter_name}) && $self->{option_results}->{filter_name} ne '' &&
$name !~ /$self->{option_results}->{filter_name}/) {
$self->{output}->output_add(long_msg => "skipping '" . $name . "': no matching filter.", debug => 1);
next;
}
my $read_io = $result->{$container_id}->{Stats}->{blkio_stats}->{io_service_bytes_recursive}->[0]->{value};
my $write_io = $result->{$container_id}->{Stats}->{blkio_stats}->{io_service_bytes_recursive}->[1]->{value};
$self->{containers}->{$container_id} = {
display => defined($self->{option_results}->{use_name}) ? $name : $container_id,
name => $name,
state => $result->{$container_id}->{State},
read_io => $read_io,
write_io => $write_io,
cpu_total_usage => $result->{$container_id}->{Stats}->{cpu_stats}->{cpu_usage}->{total_usage},
cpu_system_usage => $result->{$container_id}->{Stats}->{cpu_stats}->{system_cpu_usage},
cpu_number => scalar(@{$result->{$container_id}->{Stats}->{cpu_stats}->{cpu_usage}->{percpu_usage}}),
memory_usage => $result->{$container_id}->{Stats}->{memory_stats}->{usage},
memory_total => $result->{$container_id}->{Stats}->{memory_stats}->{limit},
};
foreach my $interface (keys %{$result->{$container_id}->{Stats}->{networks}}) {
my $name = defined($self->{option_results}->{use_name}) ? $name : $container_id;
$name .= '.' . $interface;
$self->{containers_traffic}->{$name} = {
display => $name,
traffic_in => $result->{$container_id}->{Stats}->{networks}->{$interface}->{rx_bytes} * 8,
traffic_out => $result->{$container_id}->{Stats}->{networks}->{$interface}->{tx_bytes} * 8,
};
}
}
if (scalar(keys %{$self->{containers}}) <= 0) {
$self->{output}->add_option_msg(short_msg => "No container found.");
$self->{output}->option_exit();
}
my $hostnames = $options{custom}->get_hostnames();
$self->{cache_name} = "docker_" . $self->{mode} . '_' . join('_', @$hostnames) . '_' . $options{custom}->get_port() . '_' .
(defined($self->{option_results}->{filter_counters}) ? md5_hex($self->{option_results}->{filter_counters}) : md5_hex('all')) . '_' .
(defined($self->{option_results}->{filter_name}) ? md5_hex($self->{option_results}->{filter_name}) : md5_hex('all')) . '_' .
(defined($self->{option_results}->{container_id}) ? md5_hex($self->{option_results}->{container_id}) : md5_hex('all')) . '_' .
(defined($self->{option_results}->{container_name}) ? md5_hex($self->{option_results}->{container_name}) : md5_hex('all'));
}
1;
__END__
=head1 MODE
Check container usage.
=over 8
=item B<--container-id>
Exact container ID.
=item B<--container-name>
Exact container name (if multiple names: names separated by ':').
=item B<--use-name>
Use docker name for perfdata and display.
=item B<--filter-name>
Filter by container name (can be a regexp).
=item B<--filter-counters>
Only display some counters (regexp can be used).
Example: --filter-counters='^container-status$'
=item B<--warning-*>
Threshold warning.
Can be: 'read-iops', 'write-iops', 'traffic-in', 'traffic-out',
'cpu' (%), 'memory' (%).
=item B<--critical-*>
Threshold critical.
Can be: 'read-iops', 'write-iops', 'traffic-in', 'traffic-out',
'cpu' (%), 'memory' (%).
=item B<--warning-container-status>
Set warning threshold for status (Default: -)
Can used special variables like: %{name}, %{state}.
=item B<--critical-container-status>
Set critical threshold for status (Default: -).
Can used special variables like: %{name}, %{state}.
=back
=cut
| wilfriedcomte/centreon-plugins | cloud/docker/restapi/mode/containerusage.pm | Perl | apache-2.0 | 16,281 |
#!/usr/bin/env perl
# 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.
# Figure out which seq_regions are non-redundant and set the appropriate
# attribute in seq_region_attrib
use strict;
use warnings;
use DBI;
use Getopt::Long;
use Bio::EnsEMBL::DBSQL::DBAdaptor;
use Bio::EnsEMBL::DBSQL::SliceAdaptor;
my ($host, $port, $user, $password, $db, $verbose, $check);
$host = "127.0.0.1";
$port = 3306;
$password = "";
$user = "ensro";
GetOptions ('host=s' => \$host,
'user=s' => \$user,
'password=s' => \$password,
'port=s' => \$port,
'db=s' => \$db,
'verbose' => \$verbose,
'check' => \$check,
'help' => sub { &show_help(); exit 1;} );
die "Host must be specified" unless $host;
die "Database must be specified" unless $db;
my $dbi = DBI->connect("dbi:mysql:host=$host;port=$port;database=$db", "$user", "$password", {'RaiseError' => 1}) || die "Can't connect to target DB";
# ----------------------------------------
# check that there is an entry in the attrib_type table for nonredundant
# if there is, cache the ID for later; if not, make one
my $nr_attrib_type_id;
my $sth = $dbi->prepare("SELECT attrib_type_id FROM attrib_type WHERE code='nonredundant'");
$sth->execute();
while ( my @row= $sth->fetchrow_array()) {
$nr_attrib_type_id = $row[0];
}
$sth->finish();
if ($nr_attrib_type_id) {
debug("Attribute with name nonredundant already set in attrib_type with attrib_type_id " . $nr_attrib_type_id);
} else {
debug("Attribute with name nonredundant not set in attrib_type; adding ...");
$sth = $dbi->prepare("INSERT INTO attrib_type (code, name) VALUES ('nonredundant', 'Non-redundant sequence region')");
$sth->execute();
$nr_attrib_type_id = $sth->{mysql_insertid};
debug("Added nonredundant attribute with ID " . $nr_attrib_type_id);
}
# ----------------------------------------
my $db_adaptor = new Bio::EnsEMBL::DBSQL::DBAdaptor(-user => $user,
-dbname => $db,
-host => $host,
-port => $port,
-pass => $password,
-driver => 'mysql' );
my $slice_adaptor = $db_adaptor->get_SliceAdaptor();
# Assume all entries in the top-level co-ordinate system are non-redundant
my @toplevel = @{$slice_adaptor->fetch_all('toplevel')};
debug("Got " . @toplevel . " sequence regions in the top-level co-ordinate system");
set_nr_attribute($slice_adaptor, $nr_attrib_type_id, $dbi, @toplevel);
# Rest of the co-ordinate systems, in "ascending" order
my @coord_systems = get_coord_systems_in_order($db_adaptor, $slice_adaptor);
debug("Starting pair-wise co-ordinate system comparison");
my @nr_slices; # will store non-redundant ones for later
for (my $lower_cs_idx = 0; $lower_cs_idx < @coord_systems; $lower_cs_idx++) {
for (my $higher_cs_idx = $lower_cs_idx+1; $higher_cs_idx < @coord_systems; $higher_cs_idx++) {
my $higher_cs = $coord_systems[$higher_cs_idx];
my $lower_cs = $coord_systems[$lower_cs_idx];
debug("$lower_cs:$higher_cs");
# we are interested in the slices that do *not* project onto the "higher" coordinate system
my @slices = @{$slice_adaptor->fetch_all($lower_cs)};
my $projected_hit = 0;
my $projected_miss = 0;
foreach my $slice (@slices) {
my @projected = @{$slice->project($higher_cs)};
if (@projected > 0) {
$projected_hit++;
} else {
$projected_miss++;
push @nr_slices, $slice;
}
undef @projected;
}
debug ("Projecting " . $lower_cs . " onto " . $higher_cs . ": " .
$projected_hit . " hit, " . $projected_miss . " miss out of " . @slices . " total");
undef @slices;
}
}
set_nr_attribute($slice_adaptor, $nr_attrib_type_id, $dbi, @nr_slices);
#----------------------------------------
check_non_redundant($slice_adaptor) if $check;
$sth->finish();
$dbi->disconnect();
# ----------------------------------------
# Get all the co-ordinate systems in order
# Order is descending average length
# Return an array of co-ordinate system names
sub get_coord_systems_in_order() {
my $db_adaptor = shift;
my $slice_adaptor = shift;
debug("Ordering co-ordinate systems by average length");
my $cs_adaptor = $db_adaptor->get_CoordSystemAdaptor();
my @coord_system_objs = @{$cs_adaptor->fetch_all()};
# Calculate average lengths
my %lengths;
foreach my $cs (@coord_system_objs) {
my @slices = @{$slice_adaptor->fetch_all($cs->name())};
my $total_len = 0;
foreach my $slice (@slices) {
$total_len += $slice->length();
}
if ($total_len > 0) {
$lengths{$cs->name()} = $total_len / scalar(@slices);
} else {
$lengths{$cs->name()} = 0;
print "Warning - total length for " . $cs->name() . " is zero!\n";
}
}
my @coord_systems = sort { $lengths{$a} <=> $lengths{$b} } keys %lengths;
foreach my $cs_name (@coord_systems) {
debug("Co-ord system: " . $cs_name . " Average length: " . int $lengths{$cs_name});
}
debug("Got co-ordinate systems in order: " . join(', ', @coord_systems));
return @coord_systems;
}
# ----------------------------------------------------------------------
# Misc / utility functions
sub show_help {
print "Usage: perl set_non_redundant_attribs.pl {options}\n";
print "Where options are:\n";
print " --host {hostname} The database host.\n";
print " --user {username} The database user. Must have write permissions\n";
print " --password {pass} The password for user, if required.\n";
print " --port {folder} The database port to use.\n";
print " --db {schema} The name of the database\n";
print " --check Read back non-redundant slices from SliceAdaptor\n";
print " --verbose Print extra output information\n";
}
# ----------------------------------------------------------------------
sub debug {
my $str = shift;
print $str . "\n" if $verbose;
}
# ----------------------------------------------------------------------
# Set the "nonredundant" attribute on a Slice or group of Slices
# arg 1: SliceAdaptor
# arg 2: internal ID of 'nonredundant' attrib_type
# arg 3: DB connection
# arg 3..n: Slices
sub set_nr_attribute {
my ($slice_adaptor, $nr_attrib_type_id, $dbi, @targets) = @_;
debug("Setting nonredundant attribute on " . @targets . " sequence regions");
my $sth = $dbi->prepare("INSERT INTO seq_region_attrib (seq_region_id, attrib_type_id) VALUES (?,?)");
foreach my $slice (@targets) {
my $seq_region_id = $slice_adaptor->get_seq_region_id($slice);
$sth->execute($seq_region_id, $nr_attrib_type_id);
}
$sth->finish();
}
# ----------------------------------------------------------------------
sub check_non_redundant {
my $slice_adaptor = shift;
my @all = @{$slice_adaptor->fetch_all_non_redundant()};
print "Got " . @all . " non-redundant seq_regions from SliceAdaptor\n";
}
| Ensembl/ensembl | misc-scripts/surgery/set_nonredundant_attribs.pl | Perl | apache-2.0 | 7,630 |
=head1 LICENSE
See the NOTICE file distributed with this work for additional information
regarding copyright ownership.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
=head1 NAME
Bio::EnsEMBL::Compara::PipeConfig::Vertebrates::StrainsReindexMembers_conf
=head1 SYNOPSIS
init_pipeline.pl Bio::EnsEMBL::Compara::PipeConfig::Vertebrates::StrainsReindexMembers_conf -host mysql-ens-compara-prod-X -port XXXX \
-collection <collection> -member_type <protein|ncrna>
=head1 EXAMPLES
init_pipeline.pl Bio::EnsEMBL::Compara::PipeConfig::Vertebrates::StrainsReindexMembers_conf -host mysql-ens-compara-prod-X -port XXXX ...
e99 # From now on the collection and member_type parameters are only used to name the database, mlss_id is not needed anymore
-prev_tree_db murinae_ptrees_prev -collection murinae -member_type protein
-prev_tree_db murinae_nctrees_prev -collection murinae -member_type ncrna
-prev_tree_db sus_ptrees_prev -collection sus -member_type protein
-prev_tree_db sus_nctrees_prev -collection sus -member_type ncrna
e98 protein-trees
-mlss_id 40128 -member_type ncrna -prev_rel_db murinae_nctrees_prev $(mysql-ens-compara-prod-7-ensadmin details hive)
e98 ncRNA-trees
-mlss_id 40126 -member_type protein -prev_rel_db murinae_ptrees_prev $(mysql-ens-compara-prod-7-ensadmin details hive)
=head1 DESCRIPTION
A specialized version of ReindexMembers pipeline to use in Vertebrates for
strains/breeds, e.g. murinae or sus.
=head1 AUTHORSHIP
Ensembl Team. Individual contributions can be found in the GIT log.
=head1 APPENDIX
The rest of the documentation details each of the object methods.
Internal methods are usually preceded with an underscore (_)
=cut
package Bio::EnsEMBL::Compara::PipeConfig::Vertebrates::StrainsReindexMembers_conf;
use strict;
use warnings;
use base ('Bio::EnsEMBL::Compara::PipeConfig::ReindexMembers_conf');
sub default_options {
my ($self) = @_;
return {
%{$self->SUPER::default_options},
'division' => 'vertebrates',
'prev_tree_db' => $self->o('collection') . '#expr( (#member_type# eq "protein") ? "_ptrees_prev" : "_nctrees_prev" )expr#',
};
}
1;
| Ensembl/ensembl-compara | modules/Bio/EnsEMBL/Compara/PipeConfig/Vertebrates/StrainsReindexMembers_conf.pm | Perl | apache-2.0 | 2,938 |
#!/usr/bin/perl
use warnings;
use strict;
use 5.10.0;
persist();
{
my $store = 0;
sub persist {
print $store++ . " ";
}
}
persist();
persist();
persist();
| jmcveigh/komodo-tools | scripts/perl/named_blocks/begin.pl | Perl | bsd-2-clause | 178 |
package Net::OpenVPN::Auth::IMAP;
@ISA = qw(Net::OpenVPN::Auth);
use strict;
use warnings;
use IO::Socket;
use Log::Log4perl;
=head1 NAME IMAP
Dovecot IMAP server backend authentication module
=cut
=head1 OBJECT CONSTRUCTOR
=head2 Inherited parameters
B<required> (boolean, 1) successfull authentication result is required for authentication chain to return successful authentication
B<sufficient> (boolean, 0) successful authentication result is sufficient for entire authentication chain
=over
=head2 Module specific parameters
B<host> (string, "localhost") IMAP server hostname
B<port> (integer, 143) IMAP server listening port
B<tls> (boolean, 0) Enable TLS/SSLv3 transport security. This option requires IO::Socket::SSL module
B<tls_version> (string, "tlsv1") Transport protocol type. Valid values: B<tlsv1, sslv2, sslv3>
B<tls_ciphers> (string, "HIGH") See IO::Socket::SSL
B<tls_cert_file> (string, undef) Certificate file
B<tls_key_file> (string, undef) Certificate key file
B<tls_ca_file> (string, undef) CA certificate file
B<tls_ca_path> (string, undef) CA authority directory
B<tls_verify> (hex integer, 0x00) See perldoc IO::Socket::SSL
B<timeout> (integer, 2) Timeout for socket operations
=cut
sub new {
my $proto = shift;
my $class = ref($proto) || $proto;
my $self = $class->SUPER::new(@_);
##################################################
# PUBLIC VARS #
##################################################
##################################################
# PRIVATE VARS #
##################################################
$self->{_name} = "IMAP";
$self->{_log} = Log::Log4perl->get_logger(__PACKAGE__);
bless($self, $class);
$self->clearParams();
$self->_init();
$self->setParams(@_);
return $self;
}
sub clearParams {
my $self = shift;
$self->SUPER::clearParams();
$self->{host} = "localhost";
$self->{port} = 143;
$self->{timeout} = 2;
$self->{tls} = 0;
$self->{tls_version} = "tlsv1";
$self->{tls_ciphers} = "HIGH";
$self->{tls_cert_file} = undef;
$self->{tls_key_file} = undef;
$self->{tls_ca_file} = undef;
$self->{tls_ca_path} = undef;
$self->{tls_verify} = 0x00;
$self->{_imap} = undef;
$self->{_has_ssl} = 0;
return 1;
}
sub authenticate {
my ($self, $struct) = @_;
return 0 unless ($self->validateParamsStruct($struct));
# connect to server
return 0 unless ($self->_connect());
# send username & password
$self->{_log}->debug("Sending username '" . $struct->{username} . "' with password '" . $struct->{password} . "'");
my $r = $self->_imapCmd("LOGIN " . $struct->{username} . " " . $struct->{password});
# close connection
$self->_disconnect();
return $r;
}
sub _init {
my ($self) = @_;
# check for IO::Socket::SSL availability
eval {
require IO::Socket::SSL;
};
$self->{_has_ssl} = ($@) ? 0 : 1;
return 1;
}
sub _connect {
my ($self) = @_;
my $sock = undef;
if ($self->{tls} && ! $self->{_has_ssl}) {
$self->{error} = "Unable to use SSL/TLS secured session: Module IO::Socket::SSL is not available.";
$self->{_log}->error($self->{error});
return 0;
}
if ($self->{tls} && lc(substr($self->{tls_version}, 0, 3)) eq 'ssl') {
$self->{_log}->debug("Connecting to host: " . $self->{host} . ":" . $self->{port} . " using SSL.");
$sock = IO::Socket::SSL->new(
PeerAddr => $self->{host},
PeerPort => $self->{port},
Proto => "tcp",
ReuseAddr => 1,
Timeout => $self->{timeout},
$self->_getTlsHash()
);
} else {
$self->{_log}->debug("Connecting to host: " . $self->{host} . ":" . $self->{port} . ".");
$sock = IO::Socket::INET->new(
PeerAddr => $self->{host},
PeerPort => $self->{port},
Proto => "tcp",
ReuseAddr => 1,
Timeout => $self->{timeout}
);
}
unless (defined $sock) {
$self->{error} = "Unable to connect to server '" . $self->{host} . ":" . $self->{port} . "': $@";
$self->{_log}->error($self->{error});
return 0;
}
# read server greeting
return 0 unless ($self->_readResponse($sock));
# TLS anyone? Upgrade normal socket to SSL-one :)
if ($self->{tls} && lc($self->{tls_version}) eq 'tlsv1') {
# send starttls command
return 0 unless ($self->_imapCmd("STARTTLS", $sock));
# start TLS session
$self->{_log}->debug("Starting TLS session on unsecured socket.");
my $r = IO::Socket::SSL->start_SSL(
$sock,
$self->_getTlsHash()
);
unless ($r) {
$self->{error} = "Unable to start TLS secured session: " . $sock->errstr();
$self->{_log}->error($self->{error});
return 0;
}
$self->{_log}->debug("Successfully started TLS secured session.");
}
$self->{_log}->debug("Successfully connected.");
$self->{_imap} = $sock;
return 1;
}
sub _disconnect {
my ($self) = @_;
if ($self->{_imap}->connected()) {
$self->_imapCmd("LOGOUT");
$self->{_imap} = undef;
}
return 1;
}
sub _imapCmd {
my ($self, $cmd, $sock) = @_;
$sock = $self->{_imap} unless (defined $sock);
$self->{_cmd_idx}++;
unless (defined $sock && $sock->connected()) {
$self->{error} = "Invalid socket.";
$self->{_log}->error($self->{error});
return 0;
}
# send command
my $str = $self->{_cmd_idx} . " " . $cmd;
$self->{_log}->debug("Sending IMAP command: $str");
print $sock $str, "\r\n";
# ... & read response
return $self->_readResponse($sock);
}
sub _readResponse {
my ($self, $sock) = @_;
$sock = $self->{_imap} unless (defined $sock);
unless (defined $sock && $sock->connected()) {
$self->{error} = "Invalid socket.";
$self->{_log}->error($self->{error});
return undef;
}
while (1) {
my $line = $sock->getline();
unless (defined $line && length($line) > 0) {
$self->{error} = "Unable to read response from IMAP server: $!";
$self->{_log}->error($self->{error});
return 0;
}
$line =~ s/\s+$//g;
$self->{_log}->debug("IMAP server response: '$line'");
# mostly for welcome message
return 1 if ($line =~ m/^\*\s+OK/i);
# ignore lines starting with *
next if ($line =~ m/^\*/);
if ($line =~ m/^(\d+)\s+(OK|NO|BAD)\s+(.+)/i) {
my $code = uc($2);
return 1 if ($code eq 'OK');
$self->{error} = "Negative response received from IMAP server: $3";
$self->{_log}->error($self->{error});
return 0;
}
}
}
sub _getTlsHash {
my ($self) = @_;
my %h = (
SSL_version => $self->{tls_version},
SSL_chiper_list => $self->{tls_ciphers},
SSL_use_cert => (defined $self->{tls_cert_file}) ? 1 : 0,
SSL_cert_file => $self->{tls_cert_file},
SSL_key_file => $self->{tls_key_file},
SSL_ca_file => $self->{tls_ca_file},
SSL_ca_path => $self->{tls_ca_path},
SSL_verify_mode => $self->{tls_verify},
);
return %h;
}
=head1 AUTHOR
Brane F. Gracnar
=cut
=head1 SEE ALSO
L<Net::OpenVPN::Auth>
L<Net::OpenVPN::AuthChain>
L<IO::Socket::SSL>
=cut
# This line is mandatory...
1; | bfg/openvpn_auth | lib/Net/OpenVPN/Auth/IMAP.pm | Perl | bsd-3-clause | 6,846 |
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
=head1 NAME
Bio::EnsEMBL::Compara::Production::DBSQL::AnchorAlignAdaptor
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
=head1 APPENDIX
=cut
package Bio::EnsEMBL::Compara::Production::DBSQL::AnchorAlignAdaptor;
use Data::Dumper;
use Bio::EnsEMBL::Compara::Production::EPOanchors::AnchorAlign;
use Bio::EnsEMBL::Utils::Exception qw(throw);
use Bio::EnsEMBL::DBSQL::BaseAdaptor;
our @ISA = qw(Bio::EnsEMBL::DBSQL::BaseAdaptor);
#############################
#
# store methods
#
#############################
=head2 store
Arg[1] : one or many DnaFragChunk objects
Example : $adaptor->store($chunk);
Description: stores DnaFragChunk objects into compara database
Returntype : none
Exceptions : none
Caller : general
=cut
sub store {
my ($self, $anchor_align) = @_;
throw() unless($anchor_align);
throw() unless(UNIVERSAL::isa($anchor_align, 'Bio::EnsEMBL::Compara::Production::EPOanchors::AnchorAlign'));
my $query = qq{
INSERT INTO anchor_align
(method_link_species_set_id, anchor_id, dnafrag_id, dnafrag_start,
dnafrag_end, dnafrag_strand, score, num_of_organisms, num_of_sequences, evalue)
VALUES (?,?,?,?,?,?,?,?,?,?)};
my $sth = $self->prepare($query);
my $insertCount =
$sth->execute($anchor_align->method_link_species_set_id,
$anchor_align->anchor_id,
$anchor_align->dnafrag_id,
$anchor_align->dnafrag_start,
$anchor_align->dnafrag_end,
$anchor_align->dnafrag_strand,
$anchor_align->score,
$anchor_align->num_of_organisms,
$anchor_align->num_of_sequences,
$anchor_align->evalue,
);
if($insertCount>0) {
#sucessful insert
$anchor_align->dbID( $self->dbc->db_handle->last_insert_id(undef, undef, 'anchor_align', 'anchor_align_id') );
$sth->finish;
}
$anchor_align->adaptor($self);
return $anchor_align;
}
sub store_mapping_hits {
my $self = shift;
my $batch_records = shift;
my $out_put_mlssid = shift;
throw() unless($batch_records);
# FIXME: disconnect_when_inactive(): why do we need a LOCK here ?
my $dcs = $self->dbc->disconnect_when_inactive();
$self->dbc->disconnect_when_inactive(0);
$self->dbc->do("LOCK TABLE anchor_align WRITE");
my $query = qq{
INSERT INTO anchor_align (method_link_species_set_id, anchor_id, dnafrag_id, dnafrag_start,
dnafrag_end, dnafrag_strand, score, num_of_organisms, num_of_sequences, evalue, anchor_status)
VALUES (?,?,?,?,?,?,?,?,?,?,?)};
my $sth = $self->prepare($query);
foreach my $anchor_hits( @$batch_records ) {
$sth->execute( @{ $anchor_hits } );
}
$sth->finish;
$self->dbc->do("UNLOCK TABLES");
$self->dbc->disconnect_when_inactive($dcs);
return 1;
}
sub store_exonerate_hits {
my $self = shift;
my $batch_records = shift;
my $out_put_mlssid = shift;
throw() unless($batch_records);
my $query = qq{
INSERT INTO anchor_align (method_link_species_set_id, anchor_id, dnafrag_id, dnafrag_start,
dnafrag_end, dnafrag_strand, score, num_of_organisms, num_of_sequences)
VALUES (?,?,?,?,?,?,?,?,?)};
my $sth = $self->prepare($query);
foreach my $row(@$batch_records) {
$sth->execute( split(":", $row) );
}
$sth->finish;
return 1;
}
#=head2 store_new_method_link_species_set_id
#
# Arg[1] :
# Example :
# Description:
# Returntype : none
# Exceptions : none
# Caller : general
#
#=cut
#sub store_new_method_link_species_set_id {
# my($self) = @_;
# my $insert_sth = "insert into method_link
###############################################################################
#
# fetch methods
#
###############################################################################
=head2 fetch_dnafrag_id
Arg[1] :
Arg[2] :
Example :
Description:
Returntype :
Exceptions : none
Caller : general
=cut
sub fetch_dnafrag_id {
my $self = shift;
my($coord_sys, $dnafrag_name, $target_genome_db_id) = @_;
unless (defined($coord_sys) and defined($dnafrag_name) and defined($target_genome_db_id)) {
throw("fetch_dnafrag_id must have a coord_sys, dnafrag_name and target_genome_db_id");
}
my $query = qq{
SELECT dnafrag_id FROM dnafrag WHERE name = ? AND
coord_system_name = ? AND genome_db_id = ?};
my $sth = $self->prepare($query);
$sth->execute($dnafrag_name, $coord_sys, $target_genome_db_id) or die $self->errstr;
while (my$row = $sth->fetchrow_arrayref) {
return $row->[0];
}
}
##########################
sub get_target_file {
my $self = shift;
my($analysis_data_id, $target_genome_db_id) = @_;
my $query = qq{
SELECT data FROM analysis_data WHERE analysis_data = ?};
my $sth = $self->prepare($query);
$sth->execute($analysis_data_id) or die $self->errstr;
return $sth->fetchrow_arrayref()->[0]->{target_genomes}->{$target_genome_db_id};
}
=head2 fetch_anchors_by_genomedb_id
Arg[1] :
Arg[2] :
Example :
Description:
Returntype :
Exceptions : none
Caller : general
=cut
sub fetch_anchors_by_genomedb_id {
my ($self, $genome_db_id) = @_;
my $return_hashref;
unless (defined $genome_db_id) {
throw("fetch_anchors_by_genomedb_id must have an anchor_id and a method_link_species_set_id");
}
my $query = qq{
SELECT aa.dnafrag_id, aa.anchor_align_id, aa.anchor_id,
aa.dnafrag_start, aa.dnafrag_end
FROM anchor_align aa INNER JOIN dnafrag df ON
aa.dnafrag_id = df.dnafrag_id WHERE
df.genome_db_id = ? order by aa.dnafrag_id, aa.dnafrag_start};
my $sth = $self->prepare($query);
$sth->execute($genome_db_id) or die $self->errstr;
while (my$row = $sth->fetchrow_arrayref) {
push(@{$return_hashref->{$row->[0]}}, [ $row->[1], $row->[2], $row->[3], $row->[4] ]);
}
return $return_hashref;
}
=head2 fetch_all_by_anchor_id_and_mlss_id
Arg[1] : anchor_id, string
Arg[2] : method_link_species_set_id, string
Example : my $anchor = $anchor_align_adaptor->fetch_all_by_anchor_id_and_mlss_id($self->input_anchor_id,$self->method_link_species_set_id);
Description: returns hashref of cols. from anchor_align table using anchor_align_id as unique hash key
Returntype : hashref
Exceptions : none
Caller : general
=cut
sub fetch_all_by_anchor_id_and_mlss_id {
my ($self, $anchor_id, $method_link_species_set_id) = @_;
unless (defined $anchor_id && defined $method_link_species_set_id) {
throw("fetch_all_by_anchor_id_and_mlss_id must have an anchor_id and a method_link_species_set_id");
}
my $query = qq{
SELECT anchor_align_id, method_link_species_set_id, anchor_id,
dnafrag_id, dnafrag_start, dnafrag_end, dnafrag_strand, score,
num_of_organisms, num_of_sequences FROM anchor_align WHERE
anchor_id = ? AND method_link_species_set_id = ? AND anchor_status IS NULL};
my $sth = $self->prepare($query);
$sth->execute($anchor_id, $method_link_species_set_id) or die $self->errstr;
return $sth->fetchall_hashref("anchor_align_id");
}
=head2 fetch_dnafrag_and_genome_db_ids_by_test_mlssid
Arg[1] : method_link_species_set_id, string
Arg[2] : genome_db_ids, arrray_ref
Description: returns hashref of cols. from anchor_align table using anchor_align_id as unique hash key
Returntype : hashref
Exceptions : none
Caller : general
=cut
sub fetch_dnafrag_and_genome_db_ids_by_test_mlssid {
my ($self, $test_method_link_species_set_id, $anchor_id) = @_;
unless (defined $test_method_link_species_set_id && defined $anchor_id) {
throw("fetch_dnafrag_and_genome_db_ids_by_test_mlssid
must have a method_link_species_set_id and an anchor_id");
}
# my $question_marks = join(",", split("","?" x scalar(@$genome_db_ids)));
my $query = qq{
SELECT aa.dnafrag_id, df.genome_db_id
FROM anchor_align aa INNER JOIN dnafrag df on aa.dnafrag_id = df.dnafrag_id
WHERE aa.anchor_id = ? and aa.method_link_species_set_id = ? AND aa.anchor_status IS NULL};
# df.genome_db_id IN ($question_marks) AND aa.anchor_status IS NULL};
my $sth = $self->prepare($query);
my $genome_dbs = join(",", @$genome_db_ids);
$sth->execute($anchor_id, $test_method_link_species_set_id, @$genome_db_ids) or die;
return $sth->fetchall_arrayref;
}
=head2 fetch_all_anchor_ids_by_test_mlssid_and_genome_db_ids
Arg[1] : method_link_species_set_id, string
Arg[2] : genome_db_ids, arrray_ref
Arg[3] : anchor_id, string
Description: returns hashref of cols. from anchor_align table using anchor_align_id as unique hash key
Returntype : hashref
Exceptions : none
Caller : general
=cut
sub fetch_all_anchor_ids_by_test_mlssid_and_genome_db_ids {
my ($self, $test_method_link_species_set_id) = @_;
unless (defined $test_method_link_species_set_id) {
throw("fetch_all_anchor_ids_by_test_mlssid_and_genome_db_ids
must have a method_link_species_set_id");
}
# my $question_marks = join(",", split("","?" x scalar(@$genome_db_ids)));
my $query = qq{
SELECT distinct(aa.anchor_id)
FROM anchor_align aa INNER JOIN dnafrag df on aa.dnafrag_id = df.dnafrag_id
WHERE aa.method_link_species_set_id = ?};
# df.genome_db_id IN ($question_marks) AND aa.anchor_status IS NULL};
my $sth = $self->prepare($query);
my $genome_dbs = join(",", @$genome_db_ids);
$sth->execute($test_method_link_species_set_id) or die $self->errstr;
return $sth->fetchall_arrayref;
}
=head2 fetch_all_anchors_with_zero_strand
Arg[1] : genome_db_ids, array_reff
Arg[2] : method_link_species_set_id, string
Example : my $anchor = $anchor_align_adaptor->fetch_all_anchors_with_zero_strand($self->genome_db_ids, $self->test_method_link_species_set_id);
Description: returns arrayref of anchor_id's. from anchor_align table
Returntype : hashref
Exceptions : none
Caller : general
=cut
sub fetch_all_anchors_with_zero_strand {
my ($self, $method_link_species_set_id) = @_;
unless (defined $method_link_species_set_id) {
throw("fetch_all_anchors_with_zero_strand must have a method_link_species_set_id");
}
# my $question_marks = join(",", split("","?" x scalar(@$genome_db_ids)));
my $query = qq{
SELECT distinct(aa.anchor_id) from anchor_align aa INNER JOIN dnafrag df
ON aa.dnafrag_id = df.dnafrag_id WHERE aa.dnafrag_strand = 0 AND
aa.method_link_species_set_id = ? AND aa.anchor_status IS NULL};
my $sth = $self->prepare($query);
my $genome_dbs = join(",", @$genome_db_ids);
$sth->execute($method_link_species_set_id, @$genome_db_ids) or die $self->errstr;
return $sth->fetchall_arrayref;
}
=head2 setup_jobs_for_TrimAlignAnchor
Args : none
Example :
Description:
Returntype :
Exceptions : none
Caller : general
=cut
sub setup_jobs_for_TrimAlignAnchor {
my ($self, $input_analysis_id, $input_mlssid) = @_;
my $query = "SELECT DISTINCT(anchor_id) FROM anchor_align WHERE method_link_species_set_id = ? AND anchor_status IS NULL";
my $sth = $self->prepare($query);
my $insert = "INSERT INTO job (analysis_id, input_id) VALUES (?,?)";
my $sthi = $self->prepare($insert);
$sth->execute($input_mlssid);
foreach my $anchor_id (@{ $sth->fetchall_arrayref }) {
my $input_id = "{'anchor_id'=>" . $anchor_id->[0] . "}";
$sthi->execute($input_analysis_id, $input_id);
}
}
=head2 update_zero_strand_anchors
Arg[1] : anchor_ids, arrayref
Arg[2] : analysis_id, string
Arg[3] : method_link_species_set_id, string
Example :
Description:
Returntype :
Exceptions : none
Caller : general
=cut
sub update_zero_strand_anchors {
my ($self, $anchor_ids, $analysis_id, $method_link_species_set_id) = @_;
unless (defined $anchor_ids && defined $analysis_id && defined $method_link_species_set_id) {
throw("update_anchors_with_zero_strand must have a list of anchor_ids, an analysis_id and a method_link_species_set_id");
}
my $query = qq{update anchor_align set anchor_status = ? where method_link_species_set_id = ? and anchor_id = ?};
my $sth = $self->prepare($query);
foreach my$anchor_id(@{$anchor_ids}) {
$sth->execute($analysis_id, $method_link_species_set_id, $anchor_id->[0]) or die $self->errstr;
}
}
=head2 update_failed_anchor
Arg[1] : anchor_id, hashref
Arg[2] : current analysis_id, string
Example : $anchor_align_adaptor->update_failed_anchor($self->input_anchor_id, $self->input_analysis_id);
Description: updates anchor_status field, setting it to the current analysis_id, if the anchor fails the filters associated with the analysis_id
Returntype : none
Exceptions : none
Caller : general
=cut
sub update_failed_anchor {
my($self, $failed_anchor_hash_ref, $analysis_id_which_failed, $test_mlssid) = @_;
unless (defined $failed_anchor_hash_ref ){
throw( "No failed_anchor_id : update_failed_anchor failed");
}
unless (defined $analysis_id_which_failed){
throw("No analysis_id : update_failed_anchor failed");
}
unless (defined $test_mlssid) {
throw("No test_mlssid : update_failed_anchor failed");
}
my $update = qq{
UPDATE anchor_align SET anchor_status = ? WHERE anchor_id = ? AND method_link_species_set_id = ?};
my $sth = $self->prepare($update);
foreach my $failed_anchor(%{$failed_anchor_hash_ref}) {
$sth->execute($analysis_id_which_failed, $failed_anchor, $test_mlssid) or die $self->errstr;
}
return 1;
}
=head2 fetch_all_dnafrag_ids
Arg[1] : listref of genome_db_ids
Example :
Description:
Returntype : arrayref
Exceptions : none
Caller : general
=cut
sub fetch_all_dnafrag_ids {
my($self, $mlssid) = @_;
my $return_hashref;
my $dnafrag_query = qq{
SELECT DISTINCT(aa.dnafrag_id), df.genome_db_id FROM anchor_align aa
INNER JOIN dnafrag df on aa.dnafrag_id = df.dnafrag_id
WHERE aa.method_link_species_set_id = ?};
# WHERE df.genome_db_id = ?};
my $sth = $self->prepare($dnafrag_query);
$sth->execute($mlssid);
while(my@row = $sth->fetchrow_array) {
push(@{$return_hashref->{$row[1]}}, $row[0]);
}
return $return_hashref;
}
=head2 fetch_all_anchors_by_genome_db_id_and_mlssid
Arg[0] : genome_db_id, string
Arg[1] : mlssid, string
Example :
Description:
Returntype : arrayref
Exceptions : none
Caller : general
=cut
#HACK
sub fetch_all_anchors_by_genome_db_id_and_mlssid {
my($self, $genome_db_id, $test_mlssid) = @_;
unless (defined $genome_db_id && defined $test_mlssid) {
throw("fetch_all_anchors_by_dnafrag_id_and_test_mlssid must
have a genome_db_id and a test_mlssid");
}
my $dnafrag_query = qq{
SELECT aa.dnafrag_id, aa.anchor_align_id, aa.anchor_id, aa.dnafrag_start, aa.dnafrag_end
FROM anchor_align aa
INNER JOIN dnafrag df ON df.dnafrag_id = aa.dnafrag_id
WHERE df.genome_db_id = ? AND aa.method_link_species_set_id = ? AND anchor_status
IS NULL ORDER BY dnafrag_start, dnafrag_end};
my $sth = $self->prepare($dnafrag_query);
$sth->execute($genome_db_id, $test_mlssid) or die $self->errstr;
return $sth->fetchall_arrayref();
}
=head2 fetch_all_anchors_by_dnafrag_id_and_test_mlssid
Arg[1] : dnafrag_id, string
Example :
Description:
Returntype : arrayref
Exceptions : none
Caller : general
=cut
sub fetch_all_anchors_by_dnafrag_id_and_test_mlssid {
my($self, $dnafrag_id, $test_mlssid) = @_;
unless (defined $dnafrag_id && defined $test_mlssid) {
throw("fetch_all_anchors_by_dnafrag_id_and_test_mlssid must
have a dnafrag_id and a test_mlssid");
}
my $dnafrag_query = qq{
SELECT aa.anchor_align_id, aa.anchor_id, aa.dnafrag_start, aa.dnafrag_end FROM anchor_align aa
WHERE aa.dnafrag_id = ? AND aa.method_link_species_set_id = ? AND anchor_status
IS NULL ORDER BY dnafrag_start, dnafrag_end};
my $sth = $self->prepare($dnafrag_query);
$sth->execute($dnafrag_id, $test_mlssid) or die $self->errstr;
return $sth->fetchall_arrayref();
}
=head2 fetch_all_filtered_anchors
Args : none
Example :
Description:
Returntype : none
Exceptions : none
Caller : general
=cut
sub fetch_all_filtered_anchors {
my($self) = @_;
my %Return_hash;
my $fetch_query = qq{
SELECT anchor_id, dnafrag_id, dnafrag_start, dnafrag_end, num_of_sequences, num_of_organisms
FROM anchor_align WHERE anchor_status IS NULL ORDER BY dnafrag_id, dnafrag_start, dnafrag_end};
my $sth = $self->prepare($fetch_query);
$sth->execute() or die $self->errstr;
my$array_ref = $sth->fetchall_arrayref();
for(my$i=0;$i<@{$array_ref};$i++) {
push(@{$Return_hash{$array_ref->[$i]->[1]}},
[ $array_ref->[$i]->[0], $array_ref->[$i]->[2], $array_ref->[$i]->[3], $array_ref->[$i]->[4], $array_ref->[$i]->[5] ]);
# [ anchor_id, dnafrag_start, dnafrag_end, num_of_seqs_that_hit_the_genomic_position, num_of_organisms_from_which_seqs_derived ]
splice(@{$array_ref}, $i, 1); #reduce momory used
$i--;
}
return \%Return_hash;
}
=head2 fetch_by_dbID
Arg [1] : int $dbID
Example :
Description: Returns the AnchorAlign obejcts with this anchor_align_id
Returntype : Bio::EnsEMBL::Compara::Production::EPOanchors::AnchorAlign object
Exceptions :
Caller : general
=cut
sub fetch_by_dbID {
my ($self, $id) = @_;
unless (defined $id) {
throw("fetch_by_dbID must have an id");
}
my @tabs = $self->_tables;
my ($name, $syn) = @{$tabs[0]};
#construct a constraint like 't1.table1_id = 1'
my $constraint = "${syn}.${name}_id = $id";
#return first element of _generic_fetch list
my ($obj) = @{$self->_generic_fetch($constraint)};
return $obj;
}
=head2 fetch_all_by_MethodLinkSpeciesSet
Arg [1] : Bio::EnsEMBL::Compara::MethodLinkSpeciesSet $mlss
Example :
Description: Returns all the AnchorAlign obejcts for this MethodLinkSpeciesSet
Returntype : listref of Bio::EnsEMBL::Compara::Production::EPOanchors::AnchorAlign objects
Exceptions :
Caller : general
=cut
sub fetch_all_by_MethodLinkSpeciesSet {
my ($self, $method_link_species_set) = @_;
unless (UNIVERSAL::isa($method_link_species_set, "Bio::EnsEMBL::Compara::MethodLinkSpeciesSet")) {
throw("[$method_link_species_set] must be a Bio::EnsEMBL::Compara::MethodLinkSpeciesSet object");
}
my @tabs = $self->_tables;
my ($name, $syn) = @{$tabs[0]};
#construct a constraint like 't1.table1_id = 1'
my $constraint = "aa.method_link_species_set_id = ". $method_link_species_set->dbID;
#return first element of _generic_fetch list
return $self->_generic_fetch($constraint);
}
############################
#
# INTERNAL METHODS
# (pseudo subclass methods)
#
############################
#internal method used in multiple calls above to build objects from table data
sub _tables {
my $self = shift;
return (['anchor_align', 'aa'] );
}
sub _columns {
my $self = shift;
return qw (aa.anchor_align_id
aa.method_link_species_set_id
aa.anchor_id
aa.dnafrag_id
aa.dnafrag_start
aa.dnafrag_end
aa.dnafrag_strand
aa.score
aa.num_of_organisms
aa.num_of_sequences
aa.anchor_status
);
}
sub _default_where_clause {
my $self = shift;
return '';
}
sub _final_clause {
my $self = shift;
$self->{'_final_clause'} = shift if(@_);
return $self->{'_final_clause'};
}
sub _objs_from_sth {
my ($self, $sth) = @_;
my @anchor_aligns = ();
while( my $row_hashref = $sth->fetchrow_hashref()) {
my $this_anchor_align = Bio::EnsEMBL::Compara::Production::EPOanchors::AnchorAlign->new();
$this_anchor_align->adaptor($self);
$this_anchor_align->dbID($row_hashref->{'anchor_align_id'});
$this_anchor_align->method_link_species_set_id($row_hashref->{'method_link_species_set_id'});
$this_anchor_align->anchor_id($row_hashref->{'anchor_id'});
$this_anchor_align->dnafrag_id($row_hashref->{'dnafrag_id'});
$this_anchor_align->dnafrag_start($row_hashref->{'dnafrag_start'});
$this_anchor_align->dnafrag_end($row_hashref->{'dnafrag_end'});
$this_anchor_align->dnafrag_strand($row_hashref->{'dnafrag_strand'});
$this_anchor_align->score($row_hashref->{'score'});
$this_anchor_align->num_of_organisms($row_hashref->{'num_of_organisms'});
$this_anchor_align->num_of_sequences($row_hashref->{'num_of_sequences'});
$this_anchor_align->anchor_status($row_hashref->{'anchor_status'});
push @anchor_aligns, $this_anchor_align;
}
$sth->finish;
return \@anchor_aligns;
}
=head2 _generic_fetch
Arg [1] : (optional) string $constraint
An SQL query constraint (i.e. part of the WHERE clause)
Arg [2] : (optional) string $logic_name
the logic_name of the analysis of the features to obtain
Example : $fts = $a->_generic_fetch('contig_id in (1234, 1235)', 'Swall');
Description: Performs a database fetch and returns feature objects in
contig coordinates.
Returntype : listref of Bio::EnsEMBL::Production::DnaFragChunk in contig coordinates
Exceptions : none
Caller : internal
=cut
sub _generic_fetch {
my ($self, $constraint, $join) = @_;
my @tables = $self->_tables;
my $columns = join(', ', $self->_columns());
if ($join) {
foreach my $single_join (@{$join}) {
my ($tablename, $condition, $extra_columns) = @{$single_join};
if ($tablename && $condition) {
push @tables, $tablename;
if($constraint) {
$constraint .= " AND $condition";
} else {
$constraint = " $condition";
}
}
if ($extra_columns) {
$columns .= ", " . join(', ', @{$extra_columns});
}
}
}
#construct a nice table string like 'table1 t1, table2 t2'
my $tablenames = join(', ', map({ join(' ', @$_) } @tables));
my $sql = "SELECT $columns FROM $tablenames";
my $default_where = $self->_default_where_clause;
my $final_clause = $self->_final_clause;
#append a where clause if it was defined
if($constraint) {
$sql .= " WHERE $constraint ";
if($default_where) {
$sql .= " AND $default_where ";
}
} elsif($default_where) {
$sql .= " WHERE $default_where ";
}
#append additional clauses which may have been defined
$sql .= " $final_clause" if($final_clause);
my $sth = $self->prepare($sql);
$sth->execute;
# print STDERR "sql execute finished. about to build objects\n";
return $self->_objs_from_sth($sth);
}
1;
| kumarsaurabh20/ensembl-compara | modules/Bio/EnsEMBL/Compara/Production/DBSQL/AnchorAlignAdaptor.pm | Perl | apache-2.0 | 23,145 |
#!/usr/bin/perl
$filename = $ARGV[0];
#print "filename $filename\n";
@names = ();
open($fh,"<",$filename) or die "Can't open $filename";
while ($name = <$fh>) {
$name =~ s/\n$//;
push(@names,$name);
}
close($fh);
$lic = <<'END_LICENSE'
// This file is part of the Corinthia project (http://corinthia.io).
//
// See the COPYRIGHT.txt file distributed with this work for
// information regarding copyright ownership.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
END_LICENSE
;
print($lic);
print("// This file was automatically generated from $filename\n");
print("\n");
print("export const fromString: { [key: string]: number } = {\n");
$nextId = 1;
for $name (@names) {
$upper = uc($name);
$lower = lc($name);
print(" \"$upper\": $nextId,\n");
print(" \"$lower\": $nextId,\n");
$nextId++;
}
print("};\n");
print("\n");
$nextId = 1;
for $name (@names) {
$temp = $name;
$temp =~ s/#//;
$upper = uc($temp);
print("export const HTML_$upper = $nextId;\n");
$nextId++;
}
print("export const HTML_COUNT = $nextId;\n");
| corinthia/corinthia-editorlib | src/elementtypes/genelementtypes.pl | Perl | apache-2.0 | 1,558 |
package Paws::CloudFormation::DescribeStackSetOperationOutput;
use Moose;
has StackSetOperation => (is => 'ro', isa => 'Paws::CloudFormation::StackSetOperation');
has _request_id => (is => 'ro', isa => 'Str');
1;
### main pod documentation begin ###
=head1 NAME
Paws::CloudFormation::DescribeStackSetOperationOutput
=head1 ATTRIBUTES
=head2 StackSetOperation => L<Paws::CloudFormation::StackSetOperation>
The specified stack set operation.
=head2 _request_id => Str
=cut
| ioanrogers/aws-sdk-perl | auto-lib/Paws/CloudFormation/DescribeStackSetOperationOutput.pm | Perl | apache-2.0 | 491 |
=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.
=head1 CONTACT
Ensembl <http://www.ensembl.org/info/about/contact/index.html>
=cut
=head1 NAME
GO
=head1 SYNOPSIS
mv GO.pm ~/.vep/Plugins
./vep -i variations.vcf --plugin GO
=head1 DESCRIPTION
A VEP plugin that retrieves Gene Ontology terms associated with
transcripts/translations via the Ensembl API. Requires database connection.
=cut
package GO;
use strict;
use warnings;
use Bio::EnsEMBL::Variation::Utils::BaseVepPlugin;
use base qw(Bio::EnsEMBL::Variation::Utils::BaseVepPlugin);
sub new {
my $class = shift;
my $self = $class->SUPER::new(@_);
# connect to DB for offline users
my $config = $self->{config};
my $reg = $config->{reg};
if(!defined($self->{config}->{sa})) {
$reg = 'Bio::EnsEMBL::Registry';
$reg->load_registry_from_db(
-host => $config->{host},
-user => $config->{user},
-pass => $config->{password},
-port => $config->{port},
-db_version => $config->{db_version},
-species => $config->{species} =~ /^[a-z]+\_[a-z]+/i ? $config->{species} : undef,
-verbose => $config->{verbose},
-no_cache => $config->{no_slice_cache},
);
}
return $self;
}
sub version {
return 73;
}
sub feature_types {
return ['Transcript'];
}
sub get_header_info {
return { 'GO' => 'GO terms associated with protein product'};
}
sub run {
my ($self, $tva) = @_;
my $tr = $tva->transcript->translation;
return {} unless defined($tr);
my $entries = $tr->get_all_DBEntries('GO');
my $string = join(",", map {$_->display_id.':'.$_->description} @$entries);
$string =~ s/\s+/\_/g;
return { GO => $string };
}
1;
| Ensembl/VEP_plugins | GO.pm | Perl | apache-2.0 | 2,387 |
package #
Date::Manip::TZ::amguat00;
# Copyright (c) 2008-2014 Sullivan Beck. All rights reserved.
# This program is free software; you can redistribute it and/or modify it
# under the same terms as Perl itself.
# This file was automatically generated. Any changes to this file will
# be lost the next time 'tzdata' is run.
# Generated on: Fri Nov 21 10:41:41 EST 2014
# Data version: tzdata2014j
# Code version: tzcode2014j
# This module contains data from the zoneinfo time zone database. The original
# data was obtained from the URL:
# ftp://ftp.iana.org/tz
use strict;
use warnings;
require 5.010000;
our (%Dates,%LastRule);
END {
undef %Dates;
undef %LastRule;
}
our ($VERSION);
$VERSION='6.48';
END { undef $VERSION; }
%Dates = (
1 =>
[
[ [1,1,2,0,0,0],[1,1,1,17,57,56],'-06:02:04',[-6,-2,-4],
'LMT',0,[1918,10,5,6,2,3],[1918,10,4,23,59,59],
'0001010200:00:00','0001010117:57:56','1918100506:02:03','1918100423:59:59' ],
],
1918 =>
[
[ [1918,10,5,6,2,4],[1918,10,5,0,2,4],'-06:00:00',[-6,0,0],
'CST',0,[1973,11,25,5,59,59],[1973,11,24,23,59,59],
'1918100506:02:04','1918100500:02:04','1973112505:59:59','1973112423:59:59' ],
],
1973 =>
[
[ [1973,11,25,6,0,0],[1973,11,25,1,0,0],'-05:00:00',[-5,0,0],
'CDT',1,[1974,2,24,4,59,59],[1974,2,23,23,59,59],
'1973112506:00:00','1973112501:00:00','1974022404:59:59','1974022323:59:59' ],
],
1974 =>
[
[ [1974,2,24,5,0,0],[1974,2,23,23,0,0],'-06:00:00',[-6,0,0],
'CST',0,[1983,5,21,5,59,59],[1983,5,20,23,59,59],
'1974022405:00:00','1974022323:00:00','1983052105:59:59','1983052023:59:59' ],
],
1983 =>
[
[ [1983,5,21,6,0,0],[1983,5,21,1,0,0],'-05:00:00',[-5,0,0],
'CDT',1,[1983,9,22,4,59,59],[1983,9,21,23,59,59],
'1983052106:00:00','1983052101:00:00','1983092204:59:59','1983092123:59:59' ],
[ [1983,9,22,5,0,0],[1983,9,21,23,0,0],'-06:00:00',[-6,0,0],
'CST',0,[1991,3,23,5,59,59],[1991,3,22,23,59,59],
'1983092205:00:00','1983092123:00:00','1991032305:59:59','1991032223:59:59' ],
],
1991 =>
[
[ [1991,3,23,6,0,0],[1991,3,23,1,0,0],'-05:00:00',[-5,0,0],
'CDT',1,[1991,9,7,4,59,59],[1991,9,6,23,59,59],
'1991032306:00:00','1991032301:00:00','1991090704:59:59','1991090623:59:59' ],
[ [1991,9,7,5,0,0],[1991,9,6,23,0,0],'-06:00:00',[-6,0,0],
'CST',0,[2006,4,30,5,59,59],[2006,4,29,23,59,59],
'1991090705:00:00','1991090623:00:00','2006043005:59:59','2006042923:59:59' ],
],
2006 =>
[
[ [2006,4,30,6,0,0],[2006,4,30,1,0,0],'-05:00:00',[-5,0,0],
'CDT',1,[2006,10,1,4,59,59],[2006,9,30,23,59,59],
'2006043006:00:00','2006043001:00:00','2006100104:59:59','2006093023:59:59' ],
[ [2006,10,1,5,0,0],[2006,9,30,23,0,0],'-06:00:00',[-6,0,0],
'CST',0,[9999,12,31,0,0,0],[9999,12,30,18,0,0],
'2006100105:00:00','2006093023:00:00','9999123100:00:00','9999123018:00:00' ],
],
);
%LastRule = (
);
1;
| nriley/Pester | Source/Manip/TZ/amguat00.pm | Perl | bsd-2-clause | 3,151 |
#!/usr/bin/perl
# Strips out the registry code from a properly annotated file.
# Meant to work with PIRDetect(Simple)M.nc, PIRDetect(Simple)C.nc
# (see file list below)
# Output files requires interface file PIRDetection.nc and PIRRawData.nc
#
# * Replaces by substitution
# * Removes entire lines
# ~ ex. if we have 'KrakenC;' on a line, all of it will be removed, including the ;
# * all code between (and including) $startRemove and $stopRemove are removed
# * note that the "uses" and "provides" interface for PIRDetection and
# PIRRawData must be one line each (not part of a uses or provides block).
# * matching of 'configuration {' for adding 'provide interface' to PIRDetectC
# uses exact syntax.
# * Adds in wiring of Main.StdControl->GenericComm explicitly for OscopeC to work
# in barebones test file.
#
# NOTES:
# * In Perl 6 regexes, variables don't interpolate.
# ~ Perl 6: / $var /
# is like a Perl 5: / \Q$var\E /
# * To force interpolation, you must use assertions
# ~ Assertions are delimited by <...>, where the first character
# after < determines the behavior of the assertion
# ~ A leading { after < indicates code that produces a regex to be
# interpolated into the pattern at that point:
# ex. / (<ident>) <{ cache{$1} //= get_body($1) }> /
print "Make sure you are running Perl version less than 6.\n";
print "Otherwise you will need to modify the script to interpolate\n";
print "variables in regular expressions.\n";
if ($ARGV[0] == 1) { #TestPIRDetectSimple
#for top level; interface users
%exactReplace1 = ("uses interface Attribute<uint16_t> as PIRDetection \@registry(\"PIRDetection\");", "uses interface PIRDetection;",
"uses interface Attribute<uint16_t> as PIRRawData \@registry(\"PIRRawData\");", "uses interface PIRRawData;",
"OscopeC,","OscopeC,\n GenericComm as Comm,",
"Main.StdControl -> OscopeC;", "Main.StdControl -> OscopeC;\n Main.StdControl -> Comm;",
"TestPIRDetectSimpleM.PIRDetection -> RegistryC.PIRDetection;","TestPIRDetectSimpleM.PIRDetection -> PIRDetectSimpleC;",
"TestPIRDetectSimpleM.PIRRawData -> RegistryC.PIRRawData;","TestPIRDetectSimpleM.PIRRawData -> PIRDetectSimpleC;");
#for bottom level; interface providers
%exactReplace2 = ("uses interface Attribute<uint16_t> as PIRDetection \@registry(\"PIRDetection\");", "provides interface PIRDetection;",
"uses interface Attribute<uint16_t> as PIRRawData \@registry(\"PIRRawData\");", "provides interface PIRRawData;",
"PIRDetectSimpleM.PIRRawData -> RegistryC.PIRRawData;","PIRRawData = PIRDetectSimpleM;",
"PIRDetectSimpleM.PIRDetection -> RegistryC.PIRDetection;","PIRDetection = PIRDetectSimpleM;",
"call PIRDetection.set(100)","signal PIRDetection.updated(100)",
"call PIRDetection.set(0)","signal PIRDetection.updated(0)",
"call PIRRawData.set(dataVal)","signal PIRRawData.updated(dataVal)",
"configuration PIRDetectSimpleC {",
"configuration PIRDetectSimpleC {\n provides interface PIRRawData;\n provides interface PIRDetection;");
@inputFiles1 = ("../TestPIRDetect/TestPIRDetectSimple.nc",
"../TestPIRDetect/TestPIRDetectSimpleM.nc");
@inputFiles2 = ("../../lib/PIRDetect/PIRDetectSimpleC.nc",
"../../lib/PIRDetect/PIRDetectSimpleM.nc");
} else { #TestPIRDetect
#for top level; interface users
%exactReplace1 = ("uses interface Attribute<uint16_t> as PIRDetection \@registry(\"PIRDetection\");", "uses interface PIRDetection;",
"uses interface Attribute<uint16_t> as PIRRawData \@registry(\"PIRRawData\");", "uses interface PIRRawData;",
"OscopeC,","OscopeC,\n GenericComm as Comm,",
"Main.StdControl -> OscopeC;", "Main.StdControl -> OscopeC;\n Main.StdControl -> Comm;",
"TestPIRDetectM.PIRDetection -> RegistryC.PIRDetection;","TestPIRDetectM.PIRDetection -> PIRDetectC;",
"TestPIRDetectM.PIRRawData -> RegistryC.PIRRawData;","TestPIRDetectM.PIRRawData -> PIRDetectC;");
#for bottom level; interface providers
%exactReplace2 = ("uses interface Attribute<uint16_t> as PIRDetection \@registry(\"PIRDetection\");", "provides interface PIRDetection;",
"uses interface Attribute<uint16_t> as PIRRawData \@registry(\"PIRRawData\");", "provides interface PIRRawData;",
"PIRDetectM.PIRRawData -> RegistryC.PIRRawData;","PIRRawData = PIRDetectM;",
"PIRDetectM.PIRDetection -> RegistryC.PIRDetection;","PIRDetection = PIRDetectM;",
"call PIRDetection.set(confidence)","signal PIRDetection.updated(confidence)",
"call PIRDetection.set(0)","signal PIRDetection.updated(0)",
"call PIRRawData.set(dataVal)","signal PIRRawData.updated(dataVal)",
"configuration PIRDetectC {",
"configuration PIRDetectC {\n provides interface PIRRawData;\n provides interface PIRDetection;");
@inputFiles1 = ("../TestPIRDetect/TestPIRDetect.nc",
"../TestPIRDetect/TestPIRDetectM.nc");
@inputFiles2 = ("../../lib/PIRDetect/PIRDetectC.nc",
"../../lib/PIRDetect/PIRDetectM.nc");
}
@exactRemove = ("RegistryC","KrakenC","includes Registry;");
# will also remove other lines like "Main.StdControl -> KrakenC;"
@regexRemove = ("interface Attribute");
#@regexRemove = ("interface Attribute<\\w+> as \\w+ @registry\(\"\\w+\"\);");
$startRemove = "//////////Registry Code Start//////////";
$stopRemove = "//////////Registry Code Stop//////////";
#Debugging
# foreach $regex (@regexRemove) {
# print "$regex\n";
# }
# foreach $exactRep (keys %exactReplace) {
# print "$exactRep\n";
# }
foreach $file (@inputFiles1) {
&parsePrint(1);
}
foreach $file (@inputFiles2) {
&parsePrint(2);
}
sub parsePrint {
$useProvide = $_[0];
#print ">>> DEBUG: $useProvide\n";
$remFlag = 0;
$outFile = $file;
$outFile =~ s/[.\/\w]+\///;
print "######## $outFile ########\n";
open(INFILE,$file);
open(OUTFILE,">$outFile");
while ($ln = <INFILE>) {
if ($ln =~ /\Q$startRemove\E/) {$remFlag++};
if ($ln =~ /\Q$stopRemove\E/) {$remFlag--};
if ($remFlag <= 0) {
SWITCH: {
if ($ln =~ /\Q$stopRemove\E/) {
print "REMOVING_BLOCK: ".$ln;
last SWITCH;
}
if ($useProvide == 1) {
foreach $exactRep (keys %exactReplace1) {
if($ln =~ /\Q$exactRep\E/) {
print "EXACT_REPLACE: ".$ln;
$ln =~ s/\Q$exactRep\E/$exactReplace1{$exactRep}/;
print OUTFILE $ln;
last SWITCH;
}
}
} elsif ($useProvide == 2) {
foreach $exactRep (keys %exactReplace2) {
if($ln =~ /\Q$exactRep\E/) {
print "EXACT_REPLACE: ".$ln;
$ln =~ s/\Q$exactRep\E/$exactReplace2{$exactRep}/;
print OUTFILE $ln;
last SWITCH;
}
}
}
foreach $exactRem (@exactRemove) {
if($ln =~/\Q$exactRem\E/) {
print "EXACT_REMOVE: ".$ln;
last SWITCH;
}
}
foreach $regEx (@regexRemove) {
if ($ln =~ /$regEx/) { #modify for perl 6
print "REGEX_REMOVED: ".$ln;
last SWITCH;
}
}
print OUTFILE $ln;
} #SWITCH
} else {
print "REMOVING_BLOCK: ".$ln;
} #if $remFlag
} #while
close(INFILE);
close(OUTFILE);
print "\n";
}
| fresskarma/tinyos-1.x | contrib/nestfe/nesc/apps/TestPIRDetectNoReg/strip_registry.pl | Perl | bsd-3-clause | 7,260 |
# !!!!!!! 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';
10980 1099F
END
| Bjay1435/capstone | rootfs/usr/share/perl/5.18.2/unicore/lib/Blk/Meroiti2.pl | Perl | mit | 435 |
=pod
=begin comment
This is a recommended way to describe OSSL_STORE loaders,
"ossl_store-{name}", where {name} is replaced with the name of the
scheme it implements, in man section 7.
=end comment
=head1 NAME
ossl_store-file - The store 'file' scheme loader
=head1 SYNOPSIS
=for openssl generic
#include <openssl/store.h>
=head1 DESCRIPTION
Support for the 'file' scheme is built into C<libcrypto>.
Since files come in all kinds of formats and content types, the 'file'
scheme has its own layer of functionality called "file handlers",
which are used to try to decode diverse types of file contents.
In case a file is formatted as PEM, each called file handler receives
the PEM name (everything following any 'C<-----BEGIN >') as well as
possible PEM headers, together with the decoded PEM body. Since PEM
formatted files can contain more than one object, the file handlers
are called upon for each such object.
If the file isn't determined to be formatted as PEM, the content is
loaded in raw form in its entirety and passed to the available file
handlers as is, with no PEM name or headers.
Each file handler is expected to handle PEM and non-PEM content as
appropriate. Some may refuse non-PEM content for the sake of
determinism (for example, there are keys out in the wild that are
represented as an ASN.1 OCTET STRING. In raw form, it's not easily
possible to distinguish those from any other data coming as an ASN.1
OCTET STRING, so such keys would naturally be accepted as PEM files
only).
=head1 NOTES
When needed, the 'file' scheme loader will require a pass phrase by
using the B<UI_METHOD> that was passed via OSSL_STORE_open().
This pass phrase is expected to be UTF-8 encoded, anything else will
give an undefined result.
The files made accessible through this loader are expected to be
standard compliant with regards to pass phrase encoding.
Files that aren't should be re-generated with a correctly encoded pass
phrase.
See L<passphrase-encoding(7)> for more information.
=head1 SEE ALSO
L<ossl_store(7)>, L<passphrase-encoding(7)>
=head1 COPYRIGHT
Copyright 2018 The OpenSSL Project Authors. All Rights Reserved.
Licensed under the Apache License 2.0 (the "License"). You may not use
this file except in compliance with the License. You can obtain a copy
in the file LICENSE in the source distribution or at
L<https://www.openssl.org/source/license.html>.
=cut
| jens-maus/amissl | openssl/doc/man7/ossl_store-file.pod | Perl | bsd-3-clause | 2,406 |
# This file is auto-generated by the Perl DateTime Suite time zone
# code generator (0.07) This code generator comes with the
# DateTime::TimeZone module distribution in the tools/ directory
#
# Generated from /tmp/ympzZnp0Uq/antarctica. Olson data version 2012c
#
# Do not edit this file directly.
#
package DateTime::TimeZone::Indian::Kerguelen;
{
$DateTime::TimeZone::Indian::Kerguelen::VERSION = '1.46';
}
use strict;
use Class::Singleton 1.03;
use DateTime::TimeZone;
use DateTime::TimeZone::OlsonDB;
@DateTime::TimeZone::Indian::Kerguelen::ISA = ( 'Class::Singleton', 'DateTime::TimeZone' );
my $spans =
[
[
DateTime::TimeZone::NEG_INFINITY,
61504531200,
DateTime::TimeZone::NEG_INFINITY,
61504531200,
0,
0,
'zzz'
],
[
61504531200,
DateTime::TimeZone::INFINITY,
61504549200,
DateTime::TimeZone::INFINITY,
18000,
0,
'TFT'
],
];
sub olson_version { '2012c' }
sub has_dst_changes { 0 }
sub _max_year { 2022 }
sub _new_instance
{
return shift->_init( @_, spans => $spans );
}
1;
| leighpauls/k2cro4 | third_party/perl/perl/vendor/lib/DateTime/TimeZone/Indian/Kerguelen.pm | Perl | bsd-3-clause | 1,017 |
#!/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/.
# ====================================================================
#
# SHA256/512 for ARMv8.
#
# Performance in cycles per processed byte and improvement coefficient
# over code generated with "default" compiler:
#
# SHA256-hw SHA256(*) SHA512
# Apple A7 1.97 10.5 (+33%) 6.73 (-1%(**))
# Cortex-A53 2.38 15.6 (+110%) 10.1 (+190%(***))
# Cortex-A57 2.31 11.6 (+86%) 7.51 (+260%(***))
#
# (*) Software SHA256 results are of lesser relevance, presented
# mostly for informational purposes.
# (**) The result is a trade-off: it's possible to improve it by
# 10% (or by 1 cycle per round), but at the cost of 20% loss
# on Cortex-A53 (or by 4 cycles per round).
# (***) Super-impressive coefficients over gcc-generated code are
# indication of some compiler "pathology", most notably code
# generated with -mgeneral-regs-only is significanty faster
# and lags behind assembly only by 50-90%.
$flavour=shift;
$output=shift;
if ($output =~ /512/) {
$BITS=512;
$SZ=8;
@Sigma0=(28,34,39);
@Sigma1=(14,18,41);
@sigma0=(1, 8, 7);
@sigma1=(19,61, 6);
$rounds=80;
$reg_t="x";
} else {
$BITS=256;
$SZ=4;
@Sigma0=( 2,13,22);
@Sigma1=( 6,11,25);
@sigma0=( 7,18, 3);
@sigma1=(17,19,10);
$rounds=64;
$reg_t="w";
}
$func="sha${BITS}_block_data_order";
($ctx,$inp,$num,$Ktbl)=map("x$_",(0..2,30));
@X=map("$reg_t$_",(3..15,0..2));
@V=($A,$B,$C,$D,$E,$F,$G,$H)=map("$reg_t$_",(20..27));
($t0,$t1,$t2,$t3)=map("$reg_t$_",(16,17,19,28));
sub BODY_00_xx {
my ($i,$a,$b,$c,$d,$e,$f,$g,$h)=@_;
my $j=($i+1)&15;
my ($T0,$T1,$T2)=(@X[($i-8)&15],@X[($i-9)&15],@X[($i-10)&15]);
$T0=@X[$i+3] if ($i<11);
$code.=<<___ if ($i<16);
#ifndef __ARMEB__
rev @X[$i],@X[$i] // $i
#endif
___
$code.=<<___ if ($i<13 && ($i&1));
ldp @X[$i+1],@X[$i+2],[$inp],#2*$SZ
___
$code.=<<___ if ($i==13);
ldp @X[14],@X[15],[$inp]
___
$code.=<<___ if ($i>=14);
ldr @X[($i-11)&15],[sp,#`$SZ*(($i-11)%4)`]
___
$code.=<<___ if ($i>0 && $i<16);
add $a,$a,$t1 // h+=Sigma0(a)
___
$code.=<<___ if ($i>=11);
str @X[($i-8)&15],[sp,#`$SZ*(($i-8)%4)`]
___
# While ARMv8 specifies merged rotate-n-logical operation such as
# 'eor x,y,z,ror#n', it was found to negatively affect performance
# on Apple A7. The reason seems to be that it requires even 'y' to
# be available earlier. This means that such merged instruction is
# not necessarily best choice on critical path... On the other hand
# Cortex-A5x handles merged instructions much better than disjoint
# rotate and logical... See (**) footnote above.
$code.=<<___ if ($i<15);
ror $t0,$e,#$Sigma1[0]
add $h,$h,$t2 // h+=K[i]
eor $T0,$e,$e,ror#`$Sigma1[2]-$Sigma1[1]`
and $t1,$f,$e
bic $t2,$g,$e
add $h,$h,@X[$i&15] // h+=X[i]
orr $t1,$t1,$t2 // Ch(e,f,g)
eor $t2,$a,$b // a^b, b^c in next round
eor $t0,$t0,$T0,ror#$Sigma1[1] // Sigma1(e)
ror $T0,$a,#$Sigma0[0]
add $h,$h,$t1 // h+=Ch(e,f,g)
eor $t1,$a,$a,ror#`$Sigma0[2]-$Sigma0[1]`
add $h,$h,$t0 // h+=Sigma1(e)
and $t3,$t3,$t2 // (b^c)&=(a^b)
add $d,$d,$h // d+=h
eor $t3,$t3,$b // Maj(a,b,c)
eor $t1,$T0,$t1,ror#$Sigma0[1] // Sigma0(a)
add $h,$h,$t3 // h+=Maj(a,b,c)
ldr $t3,[$Ktbl],#$SZ // *K++, $t2 in next round
//add $h,$h,$t1 // h+=Sigma0(a)
___
$code.=<<___ if ($i>=15);
ror $t0,$e,#$Sigma1[0]
add $h,$h,$t2 // h+=K[i]
ror $T1,@X[($j+1)&15],#$sigma0[0]
and $t1,$f,$e
ror $T2,@X[($j+14)&15],#$sigma1[0]
bic $t2,$g,$e
ror $T0,$a,#$Sigma0[0]
add $h,$h,@X[$i&15] // h+=X[i]
eor $t0,$t0,$e,ror#$Sigma1[1]
eor $T1,$T1,@X[($j+1)&15],ror#$sigma0[1]
orr $t1,$t1,$t2 // Ch(e,f,g)
eor $t2,$a,$b // a^b, b^c in next round
eor $t0,$t0,$e,ror#$Sigma1[2] // Sigma1(e)
eor $T0,$T0,$a,ror#$Sigma0[1]
add $h,$h,$t1 // h+=Ch(e,f,g)
and $t3,$t3,$t2 // (b^c)&=(a^b)
eor $T2,$T2,@X[($j+14)&15],ror#$sigma1[1]
eor $T1,$T1,@X[($j+1)&15],lsr#$sigma0[2] // sigma0(X[i+1])
add $h,$h,$t0 // h+=Sigma1(e)
eor $t3,$t3,$b // Maj(a,b,c)
eor $t1,$T0,$a,ror#$Sigma0[2] // Sigma0(a)
eor $T2,$T2,@X[($j+14)&15],lsr#$sigma1[2] // sigma1(X[i+14])
add @X[$j],@X[$j],@X[($j+9)&15]
add $d,$d,$h // d+=h
add $h,$h,$t3 // h+=Maj(a,b,c)
ldr $t3,[$Ktbl],#$SZ // *K++, $t2 in next round
add @X[$j],@X[$j],$T1
add $h,$h,$t1 // h+=Sigma0(a)
add @X[$j],@X[$j],$T2
___
($t2,$t3)=($t3,$t2);
}
$code.=<<___;
#include "arm_arch.h"
.text
.globl $func
.type $func,%function
.align 6
$func:
___
$code.=<<___ if ($SZ==4);
ldr x16,.LOPENSSL_armcap_P
adr x17,.LOPENSSL_armcap_P
add x16,x16,x17
ldr w16,[x16]
tst w16,#ARMV8_SHA256
b.ne .Lv8_entry
___
$code.=<<___;
stp x29,x30,[sp,#-128]!
add x29,sp,#0
stp x19,x20,[sp,#16]
stp x21,x22,[sp,#32]
stp x23,x24,[sp,#48]
stp x25,x26,[sp,#64]
stp x27,x28,[sp,#80]
sub sp,sp,#4*$SZ
ldp $A,$B,[$ctx] // load context
ldp $C,$D,[$ctx,#2*$SZ]
ldp $E,$F,[$ctx,#4*$SZ]
add $num,$inp,$num,lsl#`log(16*$SZ)/log(2)` // end of input
ldp $G,$H,[$ctx,#6*$SZ]
adr $Ktbl,K$BITS
stp $ctx,$num,[x29,#96]
.Loop:
ldp @X[0],@X[1],[$inp],#2*$SZ
ldr $t2,[$Ktbl],#$SZ // *K++
eor $t3,$B,$C // magic seed
str $inp,[x29,#112]
___
for ($i=0;$i<16;$i++) { &BODY_00_xx($i,@V); unshift(@V,pop(@V)); }
$code.=".Loop_16_xx:\n";
for (;$i<32;$i++) { &BODY_00_xx($i,@V); unshift(@V,pop(@V)); }
$code.=<<___;
cbnz $t2,.Loop_16_xx
ldp $ctx,$num,[x29,#96]
ldr $inp,[x29,#112]
sub $Ktbl,$Ktbl,#`$SZ*($rounds+1)` // rewind
ldp @X[0],@X[1],[$ctx]
ldp @X[2],@X[3],[$ctx,#2*$SZ]
add $inp,$inp,#14*$SZ // advance input pointer
ldp @X[4],@X[5],[$ctx,#4*$SZ]
add $A,$A,@X[0]
ldp @X[6],@X[7],[$ctx,#6*$SZ]
add $B,$B,@X[1]
add $C,$C,@X[2]
add $D,$D,@X[3]
stp $A,$B,[$ctx]
add $E,$E,@X[4]
add $F,$F,@X[5]
stp $C,$D,[$ctx,#2*$SZ]
add $G,$G,@X[6]
add $H,$H,@X[7]
cmp $inp,$num
stp $E,$F,[$ctx,#4*$SZ]
stp $G,$H,[$ctx,#6*$SZ]
b.ne .Loop
ldp x19,x20,[x29,#16]
add sp,sp,#4*$SZ
ldp x21,x22,[x29,#32]
ldp x23,x24,[x29,#48]
ldp x25,x26,[x29,#64]
ldp x27,x28,[x29,#80]
ldp x29,x30,[sp],#128
ret
.size $func,.-$func
.align 6
.type K$BITS,%object
K$BITS:
___
$code.=<<___ if ($SZ==8);
.quad 0x428a2f98d728ae22,0x7137449123ef65cd
.quad 0xb5c0fbcfec4d3b2f,0xe9b5dba58189dbbc
.quad 0x3956c25bf348b538,0x59f111f1b605d019
.quad 0x923f82a4af194f9b,0xab1c5ed5da6d8118
.quad 0xd807aa98a3030242,0x12835b0145706fbe
.quad 0x243185be4ee4b28c,0x550c7dc3d5ffb4e2
.quad 0x72be5d74f27b896f,0x80deb1fe3b1696b1
.quad 0x9bdc06a725c71235,0xc19bf174cf692694
.quad 0xe49b69c19ef14ad2,0xefbe4786384f25e3
.quad 0x0fc19dc68b8cd5b5,0x240ca1cc77ac9c65
.quad 0x2de92c6f592b0275,0x4a7484aa6ea6e483
.quad 0x5cb0a9dcbd41fbd4,0x76f988da831153b5
.quad 0x983e5152ee66dfab,0xa831c66d2db43210
.quad 0xb00327c898fb213f,0xbf597fc7beef0ee4
.quad 0xc6e00bf33da88fc2,0xd5a79147930aa725
.quad 0x06ca6351e003826f,0x142929670a0e6e70
.quad 0x27b70a8546d22ffc,0x2e1b21385c26c926
.quad 0x4d2c6dfc5ac42aed,0x53380d139d95b3df
.quad 0x650a73548baf63de,0x766a0abb3c77b2a8
.quad 0x81c2c92e47edaee6,0x92722c851482353b
.quad 0xa2bfe8a14cf10364,0xa81a664bbc423001
.quad 0xc24b8b70d0f89791,0xc76c51a30654be30
.quad 0xd192e819d6ef5218,0xd69906245565a910
.quad 0xf40e35855771202a,0x106aa07032bbd1b8
.quad 0x19a4c116b8d2d0c8,0x1e376c085141ab53
.quad 0x2748774cdf8eeb99,0x34b0bcb5e19b48a8
.quad 0x391c0cb3c5c95a63,0x4ed8aa4ae3418acb
.quad 0x5b9cca4f7763e373,0x682e6ff3d6b2b8a3
.quad 0x748f82ee5defb2fc,0x78a5636f43172f60
.quad 0x84c87814a1f0ab72,0x8cc702081a6439ec
.quad 0x90befffa23631e28,0xa4506cebde82bde9
.quad 0xbef9a3f7b2c67915,0xc67178f2e372532b
.quad 0xca273eceea26619c,0xd186b8c721c0c207
.quad 0xeada7dd6cde0eb1e,0xf57d4f7fee6ed178
.quad 0x06f067aa72176fba,0x0a637dc5a2c898a6
.quad 0x113f9804bef90dae,0x1b710b35131c471b
.quad 0x28db77f523047d84,0x32caab7b40c72493
.quad 0x3c9ebe0a15c9bebc,0x431d67c49c100d4c
.quad 0x4cc5d4becb3e42b6,0x597f299cfc657e2a
.quad 0x5fcb6fab3ad6faec,0x6c44198c4a475817
.quad 0 // terminator
___
$code.=<<___ if ($SZ==4);
.long 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5
.long 0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5
.long 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3
.long 0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174
.long 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc
.long 0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da
.long 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7
.long 0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967
.long 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13
.long 0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85
.long 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3
.long 0xd192e819,0xd6990624,0xf40e3585,0x106aa070
.long 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5
.long 0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3
.long 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208
.long 0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2
.long 0 //terminator
___
$code.=<<___;
.size K$BITS,.-K$BITS
.align 3
.LOPENSSL_armcap_P:
.quad OPENSSL_armcap_P-.
.asciz "SHA$BITS block transform for ARMv8, CRYPTOGAMS by <appro\@openssl.org>"
.align 2
___
if ($SZ==4) {
my $Ktbl="x3";
my ($ABCD,$EFGH,$abcd)=map("v$_.16b",(0..2));
my @MSG=map("v$_.16b",(4..7));
my ($W0,$W1)=("v16.4s","v17.4s");
my ($ABCD_SAVE,$EFGH_SAVE)=("v18.16b","v19.16b");
$code.=<<___;
.type sha256_block_armv8,%function
.align 6
sha256_block_armv8:
.Lv8_entry:
stp x29,x30,[sp,#-16]!
add x29,sp,#0
ld1.32 {$ABCD,$EFGH},[$ctx]
adr $Ktbl,K256
.Loop_hw:
ld1 {@MSG[0]-@MSG[3]},[$inp],#64
sub $num,$num,#1
ld1.32 {$W0},[$Ktbl],#16
rev32 @MSG[0],@MSG[0]
rev32 @MSG[1],@MSG[1]
rev32 @MSG[2],@MSG[2]
rev32 @MSG[3],@MSG[3]
orr $ABCD_SAVE,$ABCD,$ABCD // offload
orr $EFGH_SAVE,$EFGH,$EFGH
___
for($i=0;$i<12;$i++) {
$code.=<<___;
ld1.32 {$W1},[$Ktbl],#16
add.i32 $W0,$W0,@MSG[0]
sha256su0 @MSG[0],@MSG[1]
orr $abcd,$ABCD,$ABCD
sha256h $ABCD,$EFGH,$W0
sha256h2 $EFGH,$abcd,$W0
sha256su1 @MSG[0],@MSG[2],@MSG[3]
___
($W0,$W1)=($W1,$W0); push(@MSG,shift(@MSG));
}
$code.=<<___;
ld1.32 {$W1},[$Ktbl],#16
add.i32 $W0,$W0,@MSG[0]
orr $abcd,$ABCD,$ABCD
sha256h $ABCD,$EFGH,$W0
sha256h2 $EFGH,$abcd,$W0
ld1.32 {$W0},[$Ktbl],#16
add.i32 $W1,$W1,@MSG[1]
orr $abcd,$ABCD,$ABCD
sha256h $ABCD,$EFGH,$W1
sha256h2 $EFGH,$abcd,$W1
ld1.32 {$W1},[$Ktbl]
add.i32 $W0,$W0,@MSG[2]
sub $Ktbl,$Ktbl,#$rounds*$SZ-16 // rewind
orr $abcd,$ABCD,$ABCD
sha256h $ABCD,$EFGH,$W0
sha256h2 $EFGH,$abcd,$W0
add.i32 $W1,$W1,@MSG[3]
orr $abcd,$ABCD,$ABCD
sha256h $ABCD,$EFGH,$W1
sha256h2 $EFGH,$abcd,$W1
add.i32 $ABCD,$ABCD,$ABCD_SAVE
add.i32 $EFGH,$EFGH,$EFGH_SAVE
cbnz $num,.Loop_hw
st1.32 {$ABCD,$EFGH},[$ctx]
ldr x29,[sp],#16
ret
.size sha256_block_armv8,.-sha256_block_armv8
___
}
$code.=<<___;
.comm OPENSSL_armcap_P,4,4
___
{ my %opcode = (
"sha256h" => 0x5e004000, "sha256h2" => 0x5e005000,
"sha256su0" => 0x5e282800, "sha256su1" => 0x5e006000 );
sub unsha256 {
my ($mnemonic,$arg)=@_;
$arg =~ m/[qv]([0-9]+)[^,]*,\s*[qv]([0-9]+)[^,]*(?:,\s*[qv]([0-9]+))?/o
&&
sprintf ".inst\t0x%08x\t//%s %s",
$opcode{$mnemonic}|$1|($2<<5)|($3<<16),
$mnemonic,$arg;
}
}
foreach(split("\n",$code)) {
s/\`([^\`]*)\`/eval($1)/geo;
s/\b(sha256\w+)\s+([qv].*)/unsha256($1,$2)/geo;
s/\.\w?32\b//o and s/\.16b/\.4s/go;
m/(ld|st)1[^\[]+\[0\]/o and s/\.4s/\.s/go;
print $_,"\n";
}
close STDOUT;
| sgraham/nope | third_party/boringssl/src/crypto/sha/asm/sha512-armv8.pl | Perl | bsd-3-clause | 11,498 |
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
# This file is machine-generated by mktables from the Unicode
# database, Version 6.1.0. Any changes made here will be lost!
# !!!!!!! INTERNAL PERL USE ONLY !!!!!!!
# This file is for internal use by core Perl only. The format and even the
# name or existence of this file are subject to change without notice. Don't
# use it directly.
return <<'END';
10140 1018F
END
| Dokaponteam/ITF_Project | xampp/perl/lib/unicore/lib/Blk/Ancient2.pl | Perl | mit | 423 |
package MojoPlugins::Server;
#
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
#
use Mojo::Base 'Mojolicious::Plugin';
use utf8;
use Carp qw(cluck confess);
use UI::Utils;
use Data::Dumper;
use List::Util qw/shuffle/;
use constant MAX_TRIES => 20;
##To track the active server we want to use
state %active_server_for;
sub register {
my ( $self, $app, $conf ) = @_;
$app->renderer->add_helper(
# This subroutine serves as a Retry Delegate for the specified helper by managing calls to the 'active' server.
# The servers it connects to are defined in the 'Server' table with a status of 'ONLINE".
#
# If a remote server has connectivity issues, it will attempt to find the next available 'ONLINE' server
# to communicate with, if it cannot find "any" it will then return an error.
server_send_request => sub {
my $self = shift;
my $server_type = shift;
my $helper_class = shift || confess("Supply a Helper 'class'");
my $method_function = shift || confess("Supply a Helper class 'method'");
my $schema_result_file = shift || confess("Supply a schema result file, ie: 'InfluxDBHostsOnline'");
my $response;
my $active_server = $active_server_for{$schema_result_file};
my @rs = randomize_online_servers( $self, $schema_result_file );
if ( defined $active_server ) {
if ( !grep { $_ eq $active_server } @rs ) {
# active server no longer listed as available
undef $active_server;
}
else {
# remove active_server from list
@rs = grep { $_ ne $active_server } @rs;
# tack it to the end so it's not reused immediately, but still available if the only one that responds
push @rs, $active_server;
}
}
for my $server (@rs) {
# This is the magic!! Dynamically invoke the method on the util to prevent
# if-then-else
$helper_class->set_server($server);
$response = $helper_class->$method_function($self);
my $status_code = $response->{_rc};
if ( $response->is_success ) {
$self->app->log->debug("Using server, $server");
$active_server = $server;
last;
}
if ( $status_code == 500 ) {
$self->app->log->warn("Found BAD ONLINE server, $server -- skipping");
}
else {
my $content = $response->{_content};
$self->app->log->error( "Active Server Severe Error: " . $status_code . " - " . $server . " - " . $content );
}
}
$active_server_for{$schema_result_file} = $active_server;
if ( !defined $active_server ) {
# modify response
my $message =
"No $server_type servers are available. Please verify $server_type servers are set to ONLINE and are reachable from Traffic Ops.";
$response = HTTP::Response->new( 400, undef, HTTP::Headers->new, $message );
}
return { response => $response, server => $active_server };
}
);
}
sub server_id {
my $server = shift;
my $id;
if ( defined $server ) {
$id = $server->host_name . '.' . $server->domain_name . ':' . $server->tcp_port;
}
return $id;
}
sub randomize_online_servers {
my $self = shift;
my $schema_result_file = shift;
my @rs = $self->db->resultset($schema_result_file)->search();
@rs = map { server_id($_) } @rs;
# if two or more, return shuffled list with current one removed
return shuffle(@rs);
}
1;
| alficles/incubator-trafficcontrol | traffic_ops/app/lib/MojoPlugins/Server.pm | Perl | apache-2.0 | 3,813 |
package DDG::Goodie::IsAwesome::Marneus68;
# ABSTRACT: Marneus68's first Goodie
use DDG::Goodie;
use strict;
zci answer_type => "is_awesome_marneus68";
zci is_cached => 1;
name "IsAwesome Marneus68";
description "My first Goodie, it let's the world know that GitHubUsername is awesome";
primary_example_queries "duckduckhack Marneus68";
category "special";
topics "special_interest", "geek";
code_url "https://github.com/duckduckgo/zeroclickinfo-goodies/blob/master/lib/DDG/Goodie/IsAwesome/Marneus68.pm";
attribution github => ["Marneus68", "Duane Bekaert"];
triggers start => "duckduckhack marneus68";
handle remainder => sub {
return if $_;
return "Marneus68 is awesome and has successfully completed the DuckDuckHack Goodie tutorial!";
};
1;
| kavithaRajagopalan/zeroclickinfo-goodies | lib/DDG/Goodie/IsAwesome/Marneus68.pm | Perl | apache-2.0 | 762 |
% This file is part of the Attempto Parsing Engine (APE).
% Copyright 2008-2010, Kaarel Kaljurand <kaljurand@gmail.com>.
%
% The Attempto Parsing Engine (APE) is free software: you can redistribute it and/or modify it
% under the terms of the GNU Lesser General Public License as published by the Free Software
% Foundation, either version 3 of the License, or (at your option) any later version.
%
% The Attempto Parsing Engine (APE) is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
% PURPOSE. See the GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Lesser General Public License along with the Attempto
% Parsing Engine (APE). If not, see http://www.gnu.org/licenses/.
:- module(drs_to_owlswrl, [
drs_to_owlswrl/2,
drs_to_owlswrl/4
]).
:- use_module(drs_to_owlswrl_core, [
condlist_to_dlquery/2,
condition_oneof/3,
condlist_axiomlist_with_cheat/3
]).
:- use_module('../drs_to_drslist', [
drs_to_drslist/2
]).
:- use_module('../drs_to_sdrs', [
drs_to_sdrs/2
]).
:- use_module('../../logger/error_logger', [
add_error_message/4,
clear_messages/1
]).
:- use_module(drs_to_owldrs, [
drs_to_owldrs/2
]).
:- use_module(transform_anonymous, [
transform_anonymous/2
]).
:- use_module('../logicmoo_ape_utils').
/** <module> Attempto DRS to OWL 2/SWRL translator
Translate an Attempto DRS into Web Ontology Language (OWL 2),
or if this fails then to Semantic Web Rule Language (SWRL).
If the translation fails then we search for errors by traversing
the respective structure (e.g. implication) again. Note that the error
capture is not completely implemented. Sometimes the translation simply
fails and no explanatory messages are asserted.
@author Kaarel Kaljurand
@version 2010-11-14
@license LGPLv3
TODO:
==
- general:
- put "tricks" into a separate module
- low priority: add a trick: if a DRS maps to a SWRL rule which uses sameAs/differentFrom,
but replacing these with normal object properties would make the rule expressible
directly in OWL (probably SubPropertyOf with property composition),
then replace these with ace:equal/ace:differ-from (with equivalent
definitions) and express the rule in OWL syntax.
- allow:
- URGENT: John likes at least 3 cars that Mary likes. (wrong translation)
- URGENT: Which member of Attempto is a productive-developer? (currently fails)
- URGENT: support: What are the countries that contain Paris?
- Every man is a human and sees the human.
- John's age is not 21.
- John's age is 21 or is 22.
- Every man owns something that is "abc". (because we do allow: Every man owns "abc".)
- For everything X for every thing Y if X likes Y then X does not hate Y.
- Every dog hates every cat. (MAYBE)
- Mary eats some grass. (because we do allow: Everybody that eats some meat is a carnivore.)
- Every lady's pets are nothing but cats. (instead to/in addition to: Every lady's pet is nothing but cats.)
- Every lady is somebody whose pets are more than 3 cats. (instead/in addition to: Every lady is somebody whose pet is more than 3 cats.)
- John likes more than 3 women that own a car.
- Every man is himself. (currently generates SWRL, but we could generate nothing in this case)
- check:
- if the syntax is according to the spec: DataProperty, DataValue, DataType
- Are the following equivalent, if so then handle all of them (currently some are rejected):
-- t(166, 'No city overlaps-with a city that is not the city.').
-- t(167, 'Every city overlaps-with itself or does not overlap-with a city.').
-- t(168, 'If a city overlaps-with something X then X is the city or X is not a city.').
- better error messages for:
- No card is valid.
- Every man does not have to cook a chicken.
- Every singular is every singular. (from the log)
- top-level negation
- top-level disjunction
- RDF/XML (deprecated):
- There is something X. If X likes Mary then John sees Bill. (fails to be translated to RDF/XML)
- What borders itself? (otherwise OK, but fails to be translated into RDF/XML)
- improve:
- implement namespaces support, i.e. each name should actually be a term ':'(NS, Name)
- better support for anonymous individuals (don't numbervar the DRS, this would make things easier)
- seems to be fixed:
- John owns a car. John is a man. What is it?
==
*/
%:- debug(d).
%:- debug(owldrs).
%:- debug(sentence).
% Operators used in the DRS.
:- op(400, fx, -).
:- op(500, xfx, =>).
:- op(500, xfx, v).
%% drs_to_owlswrl(+Drs:term, -Owl:term) is semidet.
%% drs_to_owlswrl(+Drs:term, +IRI:atom, -Owl:term) is semidet.
%% drs_to_owlswrl(+Drs:term, +IRI:atom, +Comment:atom, -Owl:term) is semidet.
%
% Converts an Attempto DRS into OWL 2/SWRL.
% In the beginning, the DRS is modified by drs_to_owldrs/2 in order to make
% the processing more straight-forward.
%
% @param Drs is an Attempto DRS
% @param IRI is a IRI relative to which all class names are to be interpreted
% @param Comment is a comment to be inserted into the resulting ontology (currently ignored)
% @param Owl is an OWL ontology in the form 'Ontology'(IRI, Axioms) where Axioms
% is a list of axioms that correspond to the DRS conditions, in OWL FSS (Prolog notation)
drs_to_owlswrl(Drs, Owl) :-
ontology_iri(IRI),
drs_to_owlswrl(Drs, IRI, Owl).
drs_to_owlswrl(Drs, IRI, Owl) :-
drs_to_owlswrl(Drs, IRI, 'Ontology from an ACE text.', Owl).
drs_to_owlswrl(Drs, IRI, Comment, 'Ontology'(IRI, Axioms)) :-
debug(sentence, "ACE: ~w~n", [Comment]),
drs_to_drslist(Drs, DrsList),
maplist(drs_to_owlswrl_x, DrsList, AxiomList),
append(AxiomList, Axioms).
drs_to_owlswrl(_, _, _, 'Ontology'('', [])).
drs_to_owlswrl_x(Drs, Axioms) :-
copy_term(Drs, DrsCopy),
clear_messages(owl),
drs_to_sdrs(DrsCopy, SDrsCopy),
drs_to_owldrs(SDrsCopy, OwlDrs),
ape_numbervars(OwlDrs, 1, _),
debug(owldrs, "OWL DRS: ~q~n", [OwlDrs]),
drs_to_axioms(OwlDrs, Axioms),
!.
% If the DRS corresponds to a DL-Query
drs_to_axioms(Drs, Axioms) :-
process_question(Drs, Axioms).
% If the DRS corresponds to a set of OWL and/or SWRL axioms
drs_to_axioms(Drs, Axioms) :-
findall(
ref_oneof(X, OneOf),
(
member(Condition, Drs),
condition_oneof(Condition, X, OneOf)
),
RefList
),
debug(sentence, "Toplevel: ~w~n", [RefList]),
condlist_axiomlist_with_cheat(Drs, RefList, AL),
transform_anonymous(AL, Axioms).
% Only a single question is accepted, but it
% can be preceded and followed by declarative sentences.
% Examples:
% John owns a car. Mary owns the car. What is it?
% John owns a car. Mary owns the car. What is it? Bill sees the car.
% John owns a car. Mary owns the car. What is it? Bill sees John.
process_question(Conds, AxiomList) :-
select(question(QConds), Conds, RConds),
!,
append(QConds, RConds, FlatConds),
debug(d, "~w~n", [FlatConds]),
clear_messages(owl),
catch(
(
condlist_to_dlquery(FlatConds, Class),
AxiomList = ['SubClassOf'(Class, owl:'Thing')]
),
Catcher,
(
AxiomList = [],
parse_exception(Catcher, Message, Lemma, SId/TId),
add_error_message(owl, SId-TId, Lemma, Message)
)
).
parse_exception(error(Message, context(_Pred, query(_, Lemma)-Id)), Message, Lemma, Id) :- !.
parse_exception(error(Message, context(_Pred, _Arg)), Message, '', ''/'').
%% ontology_iri(?IRI:atom)
%
% @param IRI is the prefix for ACE words used as OWL names
%
ontology_iri('http://attempto.ifi.uzh.ch/ontologies/owlswrl/test').
| TeamSPoon/logicmoo_workspace | packs_sys/logicmoo_nlu/ext/ape/prolog/utils/owlswrl/drs_to_owlswrl.pl | Perl | mit | 7,516 |
package Maximus::Task::Other::SessionExpire;
use Moose;
use Maximus;
use namespace::autoclean;
with 'Maximus::Role::Task';
sub run {
my $self = shift;
$self->schema->resultset('Session')->search({expires => {'<', time()}})
->delete;
1;
}
__PACKAGE__->meta->make_immutable;
=head1 NAME
Maximus::Task::Other::SessionExpire - Delete expired sessions from the database
=head1 SYNOPSIS
use Maximus::Task::Other::SessionExpire;
$task->run();
=head1 DESCRIPTION
Delete expired sessions from the database
=head1 METHODS
=head2 run
Run task
=head1 AUTHOR
Christiaan Kras
=head1 LICENSE
Copyright (c) 2010-2013 Christiaan Kras
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
=cut
1;
| maximos/maximus-web | lib/Maximus/Task/Other/SessionExpire.pm | Perl | mit | 1,693 |
package Alatar::Model::SqlConstraint;
use strict;
use Data::Dumper;
use Alatar::Model::SqlObject;
our @ISA = qw(Alatar::Model::SqlObject);
sub new {
my ($class,$owner,$name) = @_;
my $this = $class->SUPER::new($owner,$name);
$this->{columns} = [ ];
$this->{_inheritanceConstraint} = 0;
bless($this,$class);
return $this;
}
sub getObjectType {
my ($this) = @_;
return 'SqlConstraint';
}
sub printString {
my ($this) = @_;
return $this->getObjectType() . ' : ' . $this->{name};
}
sub isInheritable {
my ($this) = @_;
return $this->{_inheritanceConstraint};
}
sub isSqlConstraint {
my ($this) = @_;
return 1;
}
sub isSqlPrimaryKeyConstraint {
my ($this) = @_;
return 0;
}
sub isSqlForeignKeyConstraint {
my ($this) = @_;
return 0;
}
sub isSqlNotNullConstraint {
my ($this) = @_;
return 0;
}
sub isSqlCheckConstraint {
my ($this) = @_;
return 0;
}
sub isSqlDefaultConstraint {
my ($this) = @_;
return 0;
}
sub isSqlUniqueConstraint {
my ($this) = @_;
return 0;
}
# Setters and getters
sub addColumn {
my ($this,$column) = @_;
push(@{$this->{columns}},$column);
return $column;
}
sub getOneColumn {
my ($this) = @_;
return $this->{columns}[0];
}
sub getColumns {
my ($this) = @_;
return @{$this->{columns}};
}
sub setColumns {
my ($this,@columns) = @_;
$this->{columns} = \@columns;
}
# visitors
# sub acceptVisitor: Abstract;
# actions
# Return a formated name for cursors and request
sub buildName {
my ($this,$name) = @_;
return ($this->getObjectType() . '_' . $name);
}
1; | olivierauverlot/alatar | Alatar/Model/SqlConstraint.pm | Perl | mit | 1,543 |
:- consult(initial1).
goal(eventually(and(at(person1, city2), next(eventually(at(person1, city3)))))).
| TeamSPoon/logicmoo_workspace | packs_sys/logicmoo_ec/test/pddl_tests/ZenoTravel/p2.pl | Perl | mit | 104 |
package #
Date::Manip::TZ::askabu00;
# 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:33:45 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 (%Dates,%LastRule);
END {
undef %Dates;
undef %LastRule;
}
our ($VERSION);
$VERSION='6.52';
END { undef $VERSION; }
%Dates = (
1 =>
[
[ [1,1,2,0,0,0],[1,1,2,4,36,48],'+04:36:48',[4,36,48],
'LMT',0,[1889,12,31,19,23,11],[1889,12,31,23,59,59],
'0001010200:00:00','0001010204:36:48','1889123119:23:11','1889123123:59:59' ],
],
1889 =>
[
[ [1889,12,31,19,23,12],[1889,12,31,23,23,12],'+04:00:00',[4,0,0],
'AFT',0,[1944,12,31,19,59,59],[1944,12,31,23,59,59],
'1889123119:23:12','1889123123:23:12','1944123119:59:59','1944123123:59:59' ],
],
1944 =>
[
[ [1944,12,31,20,0,0],[1945,1,1,0,30,0],'+04:30:00',[4,30,0],
'AFT',0,[9999,12,31,0,0,0],[9999,12,31,4,30,0],
'1944123120:00:00','1945010100:30:00','9999123100:00:00','9999123104:30:00' ],
],
);
%LastRule = (
);
1;
| jkb78/extrajnm | local/lib/perl5/Date/Manip/TZ/askabu00.pm | Perl | mit | 1,539 |
package T::MagicMock::Patcher;
use base qw/Test::Class/;
use Test::Most;
use Test::MagicMock::Patcher;
use F::SimplePackage;
1;
sub test_patcher_replaces_sub_with_given_code : Test(1) {
my $patcher = Test::MagicMock::Patcher->new('F::SimplePackage::croak', sub { return 1; })->start();
my $ret = F::SimplePackage::croak();
is($ret, 1);
}
sub test_patcher_returns_original_code_on_stop : Test(1) {
my $patcher = Test::MagicMock::Patcher->new('F::SimplePackage::croak', sub { return 1; })->start();
$patcher->stop();
dies_ok(sub { F::SimplePackage::croak() }, "original function should be restored on stop");
}
sub test_patcher_returns_original_code_when_destroyed : Test(1) {
my $patcher = Test::MagicMock::Patcher->new('F::SimplePackage::croak', sub { return 1; })->start();
undef $patcher;
dies_ok(sub { F::SimplePackage::croak() }, "original function should be restored on patcher destroy");
}
sub test_patcher_stores_original_code_in_orig_field : Test(1) {
my $orig = *F::SimplePackage::croak{CODE};
my $patcher = Test::MagicMock::Patcher->new('F::SimplePackage::croak', sub { return 1; })->start();
is($patcher->orig, $orig);
}
sub test_patcher_stores_calls : Test(1) {
my $patcher = Test::MagicMock::Patcher->new('F::SimplePackage::croak', sub { return 1; })->start();
F::SimplePackage::croak("argument");
my $calls = $patcher->calls();
is_deeply($calls, [["argument"]]);
}
sub test_patcher_stores_call_count : Test(2) {
my $patcher = Test::MagicMock::Patcher->new('F::SimplePackage::croak', sub { return 1; })->start();
F::SimplePackage::croak("argument");
is($patcher->call_count(), 1);
F::SimplePackage::croak("argument");
is($patcher->call_count(), 2);
}
| ByteInternet/test-magicmock-perl | t/tests/T/MagicMock/Patcher.pm | Perl | mit | 1,713 |
use strict;
use CXGN::Page;
my $page=CXGN::Page->new('flowerbudctob.html','html2pl converter');
$page->header('3-8 mm flower buds');
print<<END_HEREDOC;
<center>
<table summary="" width="720" cellpadding="0" cellspacing="0"
border="0">
<tr>
<td>
<center>
<h2>3-8 mm flower buds</h2>
</center>
<table summary="" width="100\%" cellspacing="5">
<tr valign="top">
<td width="20\%">Library:</td>
<td>cTOB</td>
</tr>
<tr valign="top">
<td>TIGR ID:</td>
<td>TFB</td>
</tr>
<tr valign="top">
<td>Authors:</td>
<td>Rutger van der Hoeven, Julie Bezzerides, and
Steve Tanksley</td>
</tr>
<tr valign="top">
<td>Date made:</td>
<td>09/99</td>
</tr>
<tr valign="top">
<td>Species:</td>
<td><em>Lycopersicon esculentum</em></td>
</tr>
<tr valign="top">
<td>Accession:</td>
<td>TA496</td>
</tr>
<tr valign="top">
<td>Tissue:</td>
<td>developing flower buds and/or flowers</td>
</tr>
<tr valign="top">
<td>Developmental stage:</td>
<td>0-3 mm flower buds from 4-8 week-old plants</td>
</tr>
<tr valign="top">
<td>Vector:</td>
<td>pBluescript SK(+/-)</td>
</tr>
<tr valign="top">
<td>Host:</td>
<td>SOLR</td>
</tr>
<tr valign="top">
<td>Primary pfu:</td>
<td>1.2 x 10<small><sup>7</sup></small></td>
</tr>
<tr valign="top">
<td>Number mass excised:</td>
<td>1.5 x 10<small><sup>6</sup></small></td>
</tr>
<tr valign="top">
<td>Average insert length:</td>
<td>1.7 Kb</td>
</tr>
<tr valign="top">
<td>Cloning sites:</td>
<td>5' EcoRI, 3' XhoI</td>
</tr>
<tr valign="top">
<td>Antibiotic:</td>
<td>ampicillin</td>
</tr>
<tr valign="top">
<td>Primers:</td>
<td>M13F and M13R</td>
</tr>
<tr valign="top">
<td>Comments:</td>
<td>Flower buds and flowers were taken from
greenhouse plants (4-8 weeks old, TA496). They were
immediately frozen in liquid nitrogen and then
size-separated while remaining frozen.</td>
</tr>
</table>
</td>
</tr>
</table>
</center>
END_HEREDOC
$page->footer(); | solgenomics/sgn | cgi-bin/content/libraries/flowerbudctob.pl | Perl | mit | 2,943 |
package SimpleBot::Plugin::Twitter;
##
# Twitter.pm
# SimpleBot Plugin
# Copyright (c) 2013 Joseph Huckaby
# MIT Licensed
##
use strict;
use base qw( SimpleBot::Plugin );
use Tools;
use Net::Twitter::Lite::WithAPIv1_1;
use Encode qw(decode encode);
sub init {
my $self = shift;
$self->register_commands('rt', 'follow', 'unfollow', 'following', 'followers', 'twitter');
# only init if we have the proper api keys set
foreach my $key ('ConsumerKey', 'ConsumerSecret', 'AccessToken', 'AccessTokenSecret') {
if (!$self->{config}->{$key}) { return; }
}
local $SIG{'__DIE__'} = undef;
$self->{twitter} = Net::Twitter::Lite::WithAPIv1_1->new(
ssl => 1,
consumer_key => $self->{config}->{ConsumerKey},
consumer_secret => $self->{config}->{ConsumerSecret},
access_token => $self->{config}->{AccessToken},
access_token_secret => $self->{config}->{AccessTokenSecret}
);
$self->{data}->{follow} ||= {};
# prime user data, so we don't keep RTing their last tweet on startup
foreach my $username (keys %{$self->{data}->{follow}}) {
my $tweet = $self->get_last_tweet($username);
if ($tweet) {
$self->log_debug(9, "Registered initial tweet ID for $username: " . $tweet->{id});
$self->{data}->{follow}->{$username}->{last_tweet_id} = $tweet->{id};
}
} # foreach user
}
sub config_changed {
# called automatically when configuration changes
# i.e. owner is setting up our api keys
my $self = shift;
$self->init();
}
sub twitter {
# umbrella command for all the other commands
my ($self, $cmd, $args) = @_;
my $username = $args->{who};
if (!$self->{twitter}) {
return "$username: ERROR: Twitter Plugin is not configured. Please type: !help twitter";
}
if ($cmd =~ /^(\w+)(.*)$/) {
my ($sub_cmd, $value) = ($1, $2);
$value = trim($value);
if ($self->can($sub_cmd)) { return $self->$sub_cmd($value, $args); }
else { return "$username: Unknown Twitter command: $sub_cmd"; }
}
return undef;
}
sub reload {
# reinit twitter api connection
my ($self, $cmd, $args) = @_;
my $username = $args->{who};
$self->init();
return "$username: Twitter API has been reloaded.";
}
sub rt {
# retweet someone
my ($self, $username, $args) = @_;
$username = ntu($username);
if (!$self->{twitter}) {
return "ERROR: Twitter Plugin is not configured. Please type: !help twitter";
}
$self->{bot}->forkit(
channel => nch( $args->{channel} ),
who => $args->{who_disp},
handler => '_fork_utf8_said',
run => sub {
eval {
my $tweet = $self->get_last_tweet($username);
if ($tweet) {
if ($tweet->{user} && $tweet->{user}->{screen_name}) { $username = $tweet->{user}->{screen_name}; }
$self->log_debug(9, "Retweeting: $username: " . $tweet->{text});
print 'RT @' . $username . " " . encode('UTF-8', $tweet->{text}, Encode::FB_QUIET) . "\n";
}
else { print "Could not get latest tweet for \@$username.\n"; }
}; # eval
if ($@) { print "Twitter Error: $@\n"; }
} # sub
);
return undef;
}
sub follow {
# follow someone into current channel
my ($self, $username, $args) = @_;
$username = ntu($username);
my $channel = sch($args->{channel});
if (!$self->{twitter}) {
return "ERROR: Twitter Plugin is not configured. Please type: !help twitter";
}
if ($channel eq 'msg') {
return "Twitter: Cannot follow someone in a private message channel. Please issue command in a real #channel.";
}
$self->{data}->{follow}->{$username} ||= {};
$self->{data}->{follow}->{$username}->{channel} ||= '';
if ($self->{data}->{follow}->{$username}->{channel} eq $channel) {
return "Twitter: Already following \@".$username." in \#".$channel.".";
}
# store last tweet id, so we only RT his/her NEXT tweet
my $tweet = $self->get_last_tweet($username);
if (!$tweet) {
delete $self->{data}->{follow}->{$username};
return "Twitter Error: Cannot access user \@".$username."'s timeline.";
}
$self->{data}->{follow}->{$username}->{last_tweet_id} = $tweet->{id};
$self->{data}->{follow}->{$username}->{channel} = $channel;
$self->dirty(1);
$self->log_debug(9, "Now following $username in $channel");
$self->log_debug(9, "Last Tweet: " . $tweet->{id} . ": " . $tweet->{text});
return "Twitter: Now following \@".$username." (in \#".$channel.").";
}
sub unfollow {
# unfollow someone from current channel
my ($self, $username, $args) = @_;
$username = ntu($username);
if (!$self->{twitter}) {
return "ERROR: Twitter Plugin is not configured. Please type: !help twitter";
}
if ($self->{data}->{follow}->{$username}) {
delete $self->{data}->{follow}->{$username};
$self->dirty(1);
return "Twitter: No longer following \@".$username.".";
}
else {
return "Twitter: We're not following \@".$username.".";
}
}
sub following {
# list all followers
my ($self, $value, $args) = @_;
if (!$self->{twitter}) {
return "ERROR: Twitter Plugin is not configured. Please type: !help twitter";
}
my $users = [ sort keys %{$self->{data}->{follow}} ];
if (scalar @$users) {
my $strs = [];
foreach my $username (@$users) {
my $channel = $self->{data}->{follow}->{$username}->{channel};
push @$strs, "\@" . $username . " (in \#" . $channel . ")";
}
return "Twitter: Currently following: " . join(', ', @$strs);
}
else { return "Twitter: Not following anyone at the moment."; }
}
sub followers { my $self = shift; return $self->following(@_); }
sub tick {
# monitor twitter API for changes to our followees
my $self = shift;
my $now = time();
if (!$self->{twitter}) { return; }
if (!$self->{last_twitter_check} || (($now - $self->{last_twitter_check}) >= $self->{config}->{APIPingFreq})) {
$self->{last_twitter_check} = $now;
if (!$self->{user_ping_list} || !(scalar @{$self->{user_ping_list}})) {
$self->{user_ping_list} = [ keys %{$self->{data}->{follow}} ];
}
my $username = shift @{$self->{user_ping_list}};
if ($username && $self->{data}->{follow}->{$username}) {
$self->log_debug(9, "Forking to check tweets for $username (last tweet id: " . $self->{data}->{follow}->{$username}->{last_tweet_id} . ")");
$self->{bot}->forkit(
channel => nch( $self->{data}->{follow}->{$username}->{channel} ),
handler => '_fork_utf8_said',
run => sub {
eval {
my $tweet = $self->get_last_tweet($username);
if ($tweet) { $self->log_debug(9, "Got tweet: " . $tweet->{id} . ": " . $tweet->{text}); }
if ($tweet && ($tweet->{id} ne $self->{data}->{follow}->{$username}->{last_tweet_id})) {
# new tweet for user!
$self->enqueue_plugin_task( 'update_tweet_id', {
username => $username,
new_tweet_id => $tweet->{id}
} );
if ($tweet->{user} && $tweet->{user}->{screen_name}) { $username = $tweet->{user}->{screen_name}; }
print 'RT @' . $username . " " . encode('UTF-8', $tweet->{text}, Encode::FB_QUIET) . "\n";
} # new tweet!
else {
print "\n"; # child forks always need to print something
}
}; # eval
if ($@) { print "Twitter Error: $@\n"; }
} # sub
); # fork
} # good user
} # time to ping
}
sub update_tweet_id {
# update tweeet id in data -- called by child fork via enqueue_plugin_task()
my ($self, $args) = @_;
my $username = $args->{username};
my $tweet_id = $args->{new_tweet_id};
if ($self->{data}->{follow}->{$username}) {
$self->log_debug(9, "Updating tweet ID for user $username: $tweet_id");
$self->{data}->{follow}->{$username}->{last_tweet_id} = $tweet_id;
$self->dirty(1);
}
}
sub ntu {
# ntu = normalize twitter username
my $username = lc(shift @_);
$username =~ s/^\@//;
return $username;
}
sub get_last_hashtag {
# get latest tweet for specified hashtag (or any search term)
my ($self, $search_text) = @_;
my $result = undef;
eval {
$result = $self->{twitter}->search($search_text);
};
if ($@) {
$self->log_debug(4, "Twitter API Fail: $search_text: $@");
return undef;
}
if ($result && $result->{statuses} && (scalar @{$result->{statuses}})) {
my $tweet = shift @{$result->{statuses}};
$tweet->{text} = decode_entities($tweet->{text});
# Resolve shortened URLs, i.e. http://t.co/N53Psnbi1S
$tweet->{text} =~ s@(\w+\:\/\/t\.co\/\w+)@ follow_url_redirects($1); @eg;
return $tweet;
}
return undef;
}
sub get_last_tweet {
# get last tweet for specified username
my ($self, $username) = @_;
$username = ntu($username);
# support hashtags as well as users
if ($username =~ /^\#/) { return $self->get_last_hashtag($username); }
my $result = undef;
eval {
$result = $self->{twitter}->user_timeline({
user_id => $username,
screen_name => $username,
count => 1,
exclude_replies => 1,
include_rts => 0
});
};
if ($@) {
$self->log_debug(4, "Twitter API Fail: $username: $@");
return undef;
}
if ($result && ref($result) && (scalar @$result)) {
my $tweet = shift @$result;
$tweet->{text} = decode_entities($tweet->{text});
# Resolve shortened URLs, i.e. http://t.co/N53Psnbi1S
$tweet->{text} =~ s@(\w+\:\/\/t\.co\/\w+)@ follow_url_redirects($1); @eg;
return $tweet;
}
return undef;
}
sub follow_url_redirects {
# follow url redirect and return final URL
my $url = shift;
my $done = 0;
my $count = 0;
while (!$done) {
my $ua = LWP::UserAgent->new( max_redirect => 0 );
my $resp = $ua->request( HTTP::Request->new( 'HEAD', $url ) );
my $code = $resp->code();
if (($code =~ /3\d\d/) && $resp->header('Location')) {
$url = $resp->header('Location');
$count++; if ($count > 2) { $done = 1; }
}
else { $done = 1; }
}
return $url;
}
1;
| jhuckaby/simplebot | lib/Plugins/Twitter.pm | Perl | mit | 9,624 |
# !!!!!!! 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';
V68
3057
3058
3441
3442
4987
4988
8557
8558
8573
8574
20336
20337
30334
30335
38476
38477
65817
65818
65867
65868
65874
65875
65898
65899
66291
66292
66517
66518
67677
67678
67759
67760
67839
67840
67865
67866
68050
68051
68166
68167
68335
68336
68446
68447
68478
68479
68527
68528
68862
68863
69234
69235
69413
69414
69460
69461
69732
69733
70131
70132
72812
72813
93020
93021
126083
126084
126227
126228
END
| operepo/ope | client_tools/svc/rc/usr/share/perl5/core_perl/unicore/lib/Nv/100.pl | Perl | mit | 893 |
package PersonObj;
use strict;
use BaseObject;
our @ISA =qw(BaseObject);
sub load {
my $self = shift;
my $st=qq[
SELECT
tblPerson.*,
DATE_FORMAT(dtPassportExpiry,'%d/%m/%Y') AS dtPassportExpiry,
DATE_FORMAT(dtDOB,'%d/%m/%Y') AS dtDOB,
tblPerson.dtDOB AS dtDOB_RAW,
DATE_FORMAT(tblPerson.tTimeStamp,'%d/%m/%Y') AS tTimeStamp,
DATE_FORMAT(dtNatCustomDt1,'%d/%m/%Y') AS dtNatCustomDt1,
DATE_FORMAT(dtNatCustomDt2,'%d/%m/%Y') AS dtNatCustomDt2,
DATE_FORMAT(dtNatCustomDt3,'%d/%m/%Y') AS dtNatCustomDt3,
DATE_FORMAT(dtNatCustomDt4,'%d/%m/%Y') AS dtNatCustomDt4,
DATE_FORMAT(dtNatCustomDt5,'%d/%m/%Y') AS dtNatCustomDt5,
MN.strNotes
FROM
tblPerson
LEFT JOIN tblPersonNotes as MN ON (
MN.intPersonID = tblPerson.intPersonID
)
WHERE
tblPerson.intPersonID = ?
];
my $q = $self->{'db'}->prepare($st);
$q->execute(
$self->{'ID'},
);
if($DBI::err) {
$self->LogError($DBI::err);
}
else {
$self->{'DBData'}=$q->fetchrow_hashref();
}
}
sub name {
my $self = shift;
my $surname = $self->getValue('strLocalSurname');
my $firstname = $self->getValue('strLocalFirstname');
return "$firstname $surname";
}
# Across realm check to see there is an existing member with this firstname/surname/dob and with primary club set.
# Static method.
sub already_exists {
my $class = shift;
my ($Data, $new_member, $sub_realm_id) = @_;
my $realm_id = $Data->{'Realm'};
$sub_realm_id ||= $Data->{'RealmSubType'};
my $st = qq[
SELECT
M.intPersonID,
M.strLocalFirstname,
M.strLocalSurname,
M.strEmail,
M.dtDOB,
M.strNationalNum
FROM tblPerson as M
WHERE
M.intRealmID=?
AND M.strLocalFirstname=?
AND M.strLocalSurname=?
AND M.dtDOB=?
AND M.intStatus=1
];
my $q = $Data->{'db'}->prepare($st);
$q->execute(
$realm_id,
$sub_realm_id,
$new_member->{'firstname'},
$new_member->{'surname'},
$new_member->{'dob'},
);
my @matched_members = ();
while (my $dref = $q->fetchrow_hashref()) {
push @matched_members, $dref;
}
return \@matched_members;
}
1;
| facascante/slimerp | fifs/web/PersonObj.pm | Perl | mit | 2,293 |
#!"E:\xampp\perl\bin\perl.exe"
# Copyright (C) 2002/2003 Kai Seidler, oswald@apachefriends.org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
use CGI;
use File::Basename;
$gb = dirname("$0")."/guestbook.dat";
$form = new CGI;
$f_name = CGI::escapeHTML($form->param("f_name"));
$f_email = CGI::escapeHTML($form->param("f_email"));
$f_text = CGI::escapeHTML($form->param("f_text"));
print "Content-Type: text/html; charset=iso-8859-1\n\n";
if ($f_name) {
open(FILE, ">>$gb") or die("Cannot open guestbook file");
print FILE localtime()."\n";
print FILE "$f_name\n";
print FILE "$f_email\n";
print FILE "$f_text\n";
print FILE "·\n";
close(FILE);
}
print '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"';
print ' "http://www.w3.org/TR/html4/loose.dtd">';
print '<html>';
print '<head>';
print '<meta name="author" content="Kai Oswald Seidler">';
print '<link href="xampp.css" rel="stylesheet" type="text/css">';
print '<title>Guest Book (Example for Perl)</title>';
print '</head>';
print '<body>';
print "<br><h1>Guest Book (Example for Perl)</h1>";
print "<p>A classic and simple guest book!</p>";
open(FILE, "<$gb") or die("Cannot open guestbook file");
while (!eof(FILE)) {
chomp($date = <FILE>);
chomp($name = <FILE>);
chomp($email = <FILE>);
print "<div class='small'>$date</div>";
print "<table border='0' cellpadding='4' cellspacing='1'>";
print "<tr><td class='h'>";
print "<img src='img/blank.gif' alt='' width='250' height='1'><br>";
print "Name: ".CGI::escapeHTML($name);
print "</td><td class='h'>";
print "<img src='img/blank.gif' alt='' width='250' height='1'><br>";
print "E-Mail: ".CGI::escapeHTML($email);
print "</td></tr>";
print "<tr><td class='d' colspan='2'>";
while (1 == 1){
chomp($line = <FILE>);
if ($line eq '·') {
last;
}
print CGI::escapeHTML($line)."<br>";
}
print "</td></tr>";
print "</table>";
print "<br>";
}
close (FILE);
print "<p>Add entry:</p>";
print "<form action='guestbook-en.pl' method='get'>";
print "<table border='0' cellpadding='0' cellspacing='0'>";
print "<tr><td>Name:</td><td><input type='text' size='30' name='f_name'></td></tr>";
print "<tr><td>E-Mail:</td><td> <input type='text' size='30' name='f_email'></td></tr>";
print "<tr><td>Text:</td><td> <textarea rows='3' cols='30' name='f_text'></textarea></td></tr>";
print "<tr><td></td><td><input type='submit' value='WRITE'></td></tr>";
print "</table>";
print "</form>";
print "</body>";
print "</html>";
| ArcherCraftStore/ArcherVMPeridot | htdocs/xampp/guestbook-pl.pl | Perl | apache-2.0 | 3,263 |
use IO::S4::Client;
use Data::Dumper;
$sn = $ARGV[0];
$cn = $ARGV[1];
$c = new IO::S4::Client("localhost", 2334);
$c->init();
print Dumper($c);
$c->connect({'readMode' => 'private'});
while (<STDIN>) {
chomp;
print "Sending request\n";
$c->send($sn, $cn, $_);
select(undef, undef, undef, 0.1);
print "Waiting for response...\n";
my $l = $c->recv();
print "Response: " . Dumper($l);
}
$c->disconnect();
| s4/s4 | s4-driver/examples/src/main/resources/scripts/request.pl | Perl | apache-2.0 | 424 |
#!/usr/local/bin/perl -w
use strict;
=pod
To give some background.
when you search with swish you do something like:
./swish-e -w swishdefault=foo
that says: search the field "swishdefault" for the word foo. swishdefault
is the default "metaname". When indexing, say html, swish indexes the body
text AND the title as swishdefault.
So, a document will match if "foo" is found in the title or in the body when searching
the swishdefault metaname. This is why in the sample code below supplies both the title
and description to the highlighting code.
The other part to swish is "properties". A document property is something like
the path name, title, or last modified date. Some bit of data that can be returned
with search results. So, when you do a search for "foo" swish will
return a list of documents, and for each document it will list properties.
Since properties and metanames may or may not be related, in the "config" below you see a hash that maps
one or more properties to metanames.
Note, here's a search for "apache" limiting to four results.
> ./swish-e -w apache -m 4
# SWISH format: 2.1-dev-24
# Search words: apache
# Number of hits: 120
# Search time: 0.001 seconds
# Run time: 0.006 seconds
1000 /usr/local/apache/htdocs/manual/misc/FAQ.html "Apache Server Frequently Asked Questions" 107221
973 /usr/local/apache/htdocs/manual/windows.html "Using Apache with Microsoft Windows" 21664
953 /usr/local/apache/htdocs/manual/mod/core.html "Apache Core Features" 121406
933 /usr/local/apache/htdocs/manual/netware.html "Using Apache with Novell NetWare 5" 11345
That's returning the properties rank, path, title (called swishtitle), document size by default.
Swish can also store as a property the words extracted while indexing and return that
text in the search results. This property is called "swishdescription". It's a lot
faster for swish to return this in results than to go and fetch the source document by path
and then extract out the content.
=cut
# here's the emulated results from swish placed in the "properties" hash
show() for ( 1..15 );
sub show {
my %properties = (
swishtitle => 'Apache module mod_foobar',
swishdescription => Content::content(),
);
# emulate a result object
my $result = result->new;
my $hl = PhraseHighlight->new($result, 'swishdefault' );
$hl->highlight( \%properties );
use Text::Wrap qw(wrap);
print "\nTitle: $properties{ swishtitle }\n\nDescription:\n",
wrap(' ',' ',$properties{ swishdescription }),"\n";
}
#===============================================================
package result;
use strict;
use Carp;
sub new {
bless {
config => {
description_prop => 'swishdescription',
highlight => {
package => 'PhraseHighlight',
show_words => 10, # Number of swish words words to show around highlighted word
max_words => 100, # If no words are found to highlighted then show this many words
occurrences => 6, # Limit number of occurrences of highlighted words
highlight_on => '<<on>>',
highlight_off => '<</off>>',
meta_to_prop_map => { # this maps search metatags to display properties
swishdefault => [ qw/swishtitle swishdescription/ ],
swishtitle => [ qw/swishtitle/ ],
swishdocpath => [ qw/swishdocpath/ ],
},
},
},
}, shift;
}
sub header {
my ( $self, $value ) = @_;
my %values = (
wordcharacters => 'abcdefghijklmnopqrstuvwxyz-,.',
ignorefirstchar => '.-,',
ignorelastchar => '.-,',
'stemming applied' => 0,
stopwords => 'and the is for',
);
return $values{$value} || '';
}
sub config {
my ($self, $setting, $value ) = @_;
croak "Failed to pass 'config' a setting" unless $setting;
my $cur = $self->{config}{$setting} if exists $self->{config}{$setting};
$self->{config}{$setting} = $value if $value;
return $cur;
}
# This emulates the parsing of the query passed to swish-e
sub extract_query_match {
return {
text => { ## can be text or url "layer"
swishdefault => [ ## metaname searched
[qw/directive not compatible/], ## phrase made up of three words (not stopword missing)
[qw/ foobar /], ## phrase of one word
[qw/ des* /], ## wildcard search
],
},
};
}
#=======================================================================
# Phrase Highlighting Code
#
# copyright 2001 - Bill Moseley moseley@hank.org
#
# $Id: PhraseTest.pm,v 1.1 2002/01/30 06:35:00 stas Exp $
#=======================================================================
package PhraseHighlight;
use strict;
use constant DEBUG_HIGHLIGHT => 0;
sub new {
my ( $class, $results, $metaname ) = @_;
my $self = bless {
results => $results, # just in case we need a method
settings=> $results->config('highlight'),
metaname=> $metaname,
}, $class;
# parse out the query into words
my $query = $results->extract_query_match;
# Do words exist for this layer (all text at this time) and metaname?
# This is a reference to an array of phrases and words
$self->{description_prop} = $results->config('description_prop') || '';
if ( $results->header('stemming applied') =~ /^(?:1|yes)$/i ) {
eval { require SWISH::Stemmer };
if ( $@ ) {
$results->errstr('Stemmed index needs Stemmer.pm to highlight: ' . $@);
} else {
$self->{stemmer_function} = \&SWISH::Stemmer::SwishStem;
}
}
my %stopwords = map { $_, 1 } split /\s+/, $results->header('stopwords');
$self->{stopwords} = \%stopwords;
if ( $query && exists $query->{text}{$metaname} ) {
$self->{query} = $query->{text}{$metaname};
$self->set_match_regexp;
}
return $self;
}
sub highlight {
my ( $self, $properties ) = @_;
return unless $self->{query};
my $phrase_array = $self->{query};
my $settings = $self->{settings};
my $metaname = $self->{metaname};
# Do we care about this meta?
return unless exists $settings->{meta_to_prop_map}{$metaname};
# Get the related properties
my @props = @{ $settings->{meta_to_prop_map}{$metaname} };
my %checked;
for ( @props ) {
if ( $properties->{$_} ) {
$checked{$_}++;
$self->highlight_text( \$properties->{$_}, $phrase_array );
}
}
# Truncate the description, if not processed.
my $description = $self->{description_prop};
if ( $description && !$checked{ $description } && $properties->{$description} ) {
my $max_words = $settings->{max_words} || 100;
my @words = split /\s+/, $properties->{$description};
if ( @words > $max_words ) {
$properties->{$description} = join ' ', @words[0..$max_words], '<b>...</b>';
}
}
}
#==========================================================================
#
sub highlight_text {
my ( $self, $text_ref, $phrase_array ) = @_;
my $wc_regexp = $self->{wc_regexp};
my $extract_regexp = $self->{extract_regexp};
my $last = 0;
my $settings = $self->{settings};
my $Show_Words = $settings->{show_words} || 10;
my $Occurrences = $settings->{occurrences} || 5;
my $on_flag = 'sw' . time . 'on';
my $off_flag = 'sw' . time . 'off';
my $stemmer_function = $self->{stemmer_function};
# Should really call unescapeHTML(), but then would need to escape <b> from escaping.
# Split into words. For speed, should work on a stream method.
my @words;
$self->split_by_wordchars( \@words, $text_ref );
return 'No Content saved: Check StoreDescription setting' unless @words;
my @flags; # This marks where to start and stop display.
$flags[$#words] = 0; # Extend array.
my $occurrences = $Occurrences ;
my $word_pos = $words[0] eq '' ? 2 : 0; # Start depends on if first word was wordcharacters or not
my @phrases = @{ $self->{query} };
# Remember, that the swish words are every other in @words.
WORD:
while ( $Show_Words && $word_pos * 2 < @words ) {
PHRASE:
foreach my $phrase ( @phrases ) {
print STDERR " Search phrase '@$phrase'\n" if DEBUG_HIGHLIGHT;
next PHRASE if ($word_pos + @$phrase -1) * 2 > @words; # phrase is longer than what's left
my $end_pos = 0; # end offset of the current phrase
# now compare all the words in the phrase
my ( $begin, $word, $end );
for my $match_word ( @$phrase ) {
my $cur_word = $words[ ($word_pos + $end_pos) * 2 ];
unless ( $cur_word =~ /$extract_regexp/ ) {
my $idx = ($word_pos + $end_pos) * 2;
my ( $s, $e ) = ( $idx - 10, $idx + 10 );
$s = 0 if $s < 0;
$e = @words-1 if $e >= @words;
warn "Failed to parse IgnoreFirst/Last from word '"
. (defined $cur_word ? $cur_word : '*undef')
. "' (index: $idx) word_pos:$word_pos end_pos:$end_pos total:"
. scalar @words
. "\n-search pharse words-\n"
. join( "\n", map { "$_ '$phrase->[$_]'" } 0..@$phrase -1 )
. "\n-Words-\n"
. join( "\n", map { "$_ '$words[$_]'" . ($_ == $idx ? ' <<< this word' : '') } $s..$e )
. "\n";
next PHRASE;
}
# Strip ignorefirst and ignorelast
( $begin, $word, $end ) = ( $1, $2, $3 ); # this is a waste, as it can operate on the same word over and over
my $check_word = lc $word;
if ( $end_pos && exists $self->{stopwords}{$check_word} ) {
$end_pos++;
print STDERR " Found stopword '$check_word' in the middle of phrase - * MATCH *\n" if DEBUG_HIGHLIGHT;
redo if ( $word_pos + $end_pos ) * 2 < @words; # go on to check this match word with the next word.
# No more words to match with, so go on to next pharse.
next PHRASE;
}
if ( $stemmer_function ) {
my $w = $stemmer_function->($check_word);
$check_word = $w if $w;
}
print STDERR " comparing source # (word:$word_pos offset:$end_pos) '$check_word' == '$match_word'\n" if DEBUG_HIGHLIGHT;
if ( substr( $match_word, -1 ) eq '*' ) {
next PHRASE if index( $check_word, substr($match_word, 0, length( $match_word ) - 1) ) != 0;
} else {
next PHRASE if $check_word ne $match_word;
}
print STDERR " *** Word Matched '$check_word' *** \n" if DEBUG_HIGHLIGHT;
$end_pos++;
}
print STDERR " *** PHRASE MATCHED (word:$word_pos offset:$end_pos) *** \n" if DEBUG_HIGHLIGHT;
# We are currently at the end word, so it's easy to set that highlight
$end_pos--;
if ( !$end_pos ) { # only one word
$words[$word_pos * 2] = "$begin$on_flag$word$off_flag$end";
} else {
$words[($word_pos + $end_pos) * 2 ] = "$begin$word$off_flag$end";
#Now, reload first word of match
$words[$word_pos * 2] =~ /$extract_regexp/ or die "2 Why didn't '$words[$word_pos]' =~ /$extract_regexp/?";
# Strip ignorefirst and ignorelast
( $begin, $word, $end ) = ( $1, $2, $3 ); # probably should cache this!
$words[$word_pos * 2] = "$begin$on_flag$word$end";
}
# Now, flag the words around to be shown
my $start = ($word_pos - $Show_Words + 1) * 2;
my $stop = ($word_pos + $end_pos + $Show_Words - 2) * 2;
if ( $start < 0 ) {
$stop = $stop - $start;
$start = 0;
}
$stop = $#words if $stop > $#words;
$flags[$_]++ for $start .. $stop;
# All done, and mark where to stop looking
if ( $occurrences-- <= 0 ) {
$last = $end;
last WORD;
}
# Now reset $word_pos to word following
$word_pos += $end_pos; # continue will still be executed
next WORD;
}
} continue {
$word_pos ++;
}
my @output;
$self->build_highlighted_text( \@output, \@words, \@flags, $last );
$self->join_words( \@output, $text_ref );
$self->escape_entities( $text_ref );
$self->substitue_highlight( $text_ref, $on_flag, $off_flag );
# $$text_ref = join '', @words; # interesting that this seems reasonably faster
}
#====================================================================
# Split the source text into swish and non-swish words
sub split_by_wordchars {
my ( $self, $words, $text_ref ) = @_;
my $wc_regexp = $self->{wc_regexp};
@$words = split /$wc_regexp/, $$text_ref;
}
#=======================================================================
# Put all the words together for display
#
sub build_highlighted_text {
my ( $self, $output, $words, $flags, $last ) = @_;
my $dotdotdot = ' ... ';
my $printing;
my $first = 1;
my $some_printed;
my $settings = $self->{settings};
my $Show_Words = $settings->{show_words} || 10;
if ( $Show_Words && @$words > 50 ) { # don't limit context if a small number of words
for my $i ( 0 ..$#$words ) {
if ( $last && $i >= $last && $i < $#$words ) {
push @$output, $dotdotdot;
last;
}
if ( $flags->[$i] ) {
push @$output, $dotdotdot if !$printing++ && !$first;
push @$output, $words->[$i];
$some_printed++;
} else {
$printing = 0;
}
$first = 0;
}
}
if ( !$some_printed ) {
my $Max_Words = $settings->{max_words} || 100;
for my $i ( 0 .. $Max_Words ) {
if ( $i > $#$words ) {
$printing++;
last;
}
push @$output, $words->[$i];
}
}
push @$output, $dotdotdot if !$printing;
}
#==================================================================
#
sub join_words {
my ( $self, $output, $text_ref ) = @_;
$$text_ref = join '', @$output;
}
sub escape_entities {
my ( $self, $text_ref ) = @_;
my %entities = (
'&' => '&',
'>' => '>',
'<' => '<',
'"' => '"',
);
$$text_ref =~ s/([&"<>])/$entities{$1}/ge;
}
#========================================================
# replace the highlight codes
sub substitue_highlight {
my ( $self, $text_ref, $on_flag, $off_flag ) = @_;
my $settings = $self->{settings};
my $On = $settings->{highlight_on} || '<b>';
my $Off = $settings->{highlight_off} || '</b>';
my %highlight = (
$on_flag => $On,
$off_flag => $Off,
);
$$text_ref =~ s/($on_flag|$off_flag)/$highlight{$1}/ge;
}
#============================================
# Returns compiled regular expressions for matching
#
#
sub set_match_regexp {
my $self = shift;
my $results = $self->{results};
my $wc = $results->header('wordcharacters');
my $ignoref = $results->header('ignorefirstchar');
my $ignorel = $results->header('ignorelastchar');
$wc = quotemeta $wc;
#Convert query into regular expressions
for ( $ignoref, $ignorel ) {
if ( $_ ) {
$_ = quotemeta;
$_ = "([$_]*)";
} else {
$_ = '()';
}
}
$wc .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; # Warning: dependent on tolower used while indexing
# Now, wait a minute. Look at this more, as I'd hope that making a
# qr// go out of scope would release the compiled pattern.
if ( $ENV{MOD_PERL} ) {
$self->{wc_regexp} = qr/([^$wc]+)/; # regexp for splitting into swish-words
$self->{extract_regexp} = qr/^$ignoref([$wc]+?)$ignorel$/i; # regexp for extracting out the words to compare
} else {
$self->{wc_regexp} = qr/([^$wc]+)/o; # regexp for splitting into swish-words
$self->{extract_regexp} = qr/^$ignoref([$wc]+?)$ignorel$/oi; # regexp for extracting out the words to compare
}
}
package Content;
sub content {
my $content = <<EOF;
Apache HTTP Server Version 1.3 Module mod_foobar Add this file as a link in mod/index.html
This module is contained in the mod_foobar.c file, and is/is not compiled in by default.
It provides for the foobar feature. Any document with the mime type foo/bar will be processed by this module.
Add the magic mime type to the list in magic_types.html Summary General module documentation here.
Directives ADirective Add these directives to the list in directives.html
ADirective directive Syntax: ADirective some args Default:
ADirective default value Context: context-list context-list is where this directive can appear;
allowed: server config, virtual host, directory, .htaccess Override: override required if the
directive is allowed in .htaccess files; the AllowOverride option that allows the directive.
Status: status Core if in core apache, Base if in one of the standard modules,
Extension if in an extension module (not compiled in by default) or
Experimental Module: mod_foobar Compatibility: compatibility notes Describe any compatibility issues,
such as "Only available in Apache 1.2 or later," or "The Apache syntax for this directive is not
compatible with the NCSA directive of the same name." The ADirective directive does something.
Apache HTTP Server Version 1.3
EOF
$content =~ s/\n/ /g;
return $content;
}
| Distrotech/mod_perl | docs/src/search/modules/PhraseTest.pm | Perl | apache-2.0 | 18,639 |
#!/usr/bin/env perl
# Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
use strict;
use warnings;
use Bio::EnsEMBL::Registry;
#
# This scripts maps genomic positions between two genomes, thanks to
# the BLASTZ alignment
#
my $reg = "Bio::EnsEMBL::Registry";
$reg->load_registry_from_url('mysql://anonymous@ensembldb.ensembl.org:5306');
my $alignment_type = "BLASTZ_NET";
my $set_of_species = "Homo sapiens:Pan troglodytes";
my $reference_species = "human";
#get the required adaptors
my $method_link_species_set_adaptor = $reg->get_adaptor('Multi', 'compara', 'MethodLinkSpeciesSet');
my $genome_db_adaptor = $reg->get_adaptor('Multi', 'compara', 'GenomeDB');
my $align_slice_adaptor = $reg->get_adaptor('Multi', 'compara', 'AlignSlice');
my $slice_adaptor = $reg->get_adaptor($reference_species, 'core', 'Slice');
#get the genome_db objects for human and chimp
my $genome_dbs;
foreach my $this_species (split(":", $set_of_species)) {
my $genome_db = $genome_db_adaptor->fetch_by_registry_name("$this_species");
push(@$genome_dbs, $genome_db);
}
#get the method_link_secies_set for human-chimp blastz whole genome alignments
my $method_link_species_set =
$method_link_species_set_adaptor->fetch_by_method_link_type_GenomeDBs(
$alignment_type, $genome_dbs);
die "need a file with human SNP positions \"chr:pos\" eg 6:136365469\n" unless ( -f $ARGV[0] );
open(IN, $ARGV[0]) or die;
while(<IN>) {
chomp;
my ($seq_region, $snp_pos) = split(":", $_);
my $query_slice = $slice_adaptor->fetch_by_region(undef, $seq_region, $snp_pos, $snp_pos);
my $align_slice = $align_slice_adaptor->fetch_by_Slice_MethodLinkSpeciesSet(
$query_slice, $method_link_species_set);
my $chimp_slice = $align_slice->get_all_Slices("pan_troglodytes")->[0];
my ($original_slice, $position) = $chimp_slice->get_original_seq_region_position(1);
print "human ", join(":", $seq_region, $snp_pos), "\tchimp ", join (":", $original_slice->seq_region_name, $position), "\n";
}
| dbolser-ebi/ensembl-compara | scripts/examples/dna_convertBasePositionsUsingBlastzAlignments.pl | Perl | apache-2.0 | 2,573 |
=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::HavanaAdder
=head1 SYNOPSIS
my $obj =
Bio::EnsEMBL::Analysis::RunnableDB::HavanaAdder->new( -db => $db,
-input_id => $id,
);
$obj->fetch_input;
$obj->run;
my @newfeatures = $obj->output;
=cut
# Let the code begin...
package Bio::EnsEMBL::Analysis::RunnableDB::HavanaAdder;
use warnings ;
use vars qw(@ISA);
use strict;
# Object preamble
use Bio::EnsEMBL::Analysis::RunnableDB;
use Bio::EnsEMBL::Analysis::Runnable::HavanaAdder;
use Bio::EnsEMBL::Analysis::RunnableDB::BaseGeneBuild;
use Bio::EnsEMBL::Utils::Exception qw(throw warning);
use Bio::EnsEMBL::Analysis::Config::HavanaAdder qw (
ENSEMBL_INPUT_CODING_TYPE
HAVANA_GENE_OUTPUT_BIOTYPE
MERGED_GENE_OUTPUT_BIOTYPE
ENSEMBL_GENE_OUTPUT_BIOTYPE
MERGED_TRANSCRIPT_OUTPUT_TYPE
);
@ISA = qw(Bio::EnsEMBL::Analysis::RunnableDB::BaseGeneBuild);
############################################################
=head2 new
Usage : $self->new(-DBOBJ => $db,
-INPUT_ID => $id,
-SEQFETCHER => $sf,
-ANALYSIS => $analysis,
);
Description: Creates a Bio::EnsEMBL::Analysis::RunnableDB::HavanaAdder object
Returns : A Bio::EnsEMBL::Analysis::RunnableDB::HavanaAdder object
Args : -dbobj: A Bio::EnsEMBL::DBSQL::DBAdaptor (required),
-input_id: Contig input id (required),
-seqfetcher: A Sequence Fetcher Object,
-analysis: A Bio::EnsEMBL::Analysis (optional)
=cut
sub new {
my ( $class, @args ) = @_;
my $self = $class->SUPER::new(@args);
return $self;
}
############################################################
sub input_id {
my ( $self, $arg ) = @_;
if ( defined($arg) ) {
$self->{_input_id} = $arg;
}
return $self->{_input_id};
}
############################################################
=head2 write_output
Usage : $self->write_output
Description: Writes output data to db
Returns : Nothing
Args : None
=cut
sub write_output {
my ( $self, @genes ) = @_;
print "Starting the write output process now \n";
# write genes out to a different database from the one we read
# genewise genes from.
my $db = $self->get_dbadaptor("GENEBUILD_DB");
#print "WRITE DB IS:",%$db->dbc->dbname,"\n";
# sort out analysis
my $analysis = $self->analysis;
unless ($analysis) {
$self->throw(
"an analysis logic name must be defined in the command line");
}
# my %contighash;
my $gene_adaptor = $db->get_GeneAdaptor;
# this now assummes that we are building on a single VC.
my $genebuilders = $self->get_genebuilders;
foreach my $genesbuilt ( keys %$genebuilders ) {
# my $vc = $genebuilders->{$contig}->query;
@genes = @{ $genebuilders->{$genesbuilt}->final_genes } ;
print "I have ", scalar(@genes), " genes\n";
return unless ( $#genes >= 0 );
foreach my $gene (@genes) {
$gene->analysis($analysis);
# store
eval {
$gene_adaptor->store($gene);
print STDERR "wrote gene " . $gene->dbID . " to database\n";
};
if ($@) {
warning("UNABLE TO WRITE GENE:\n$@");
}
}
}
return 1;
} ## end sub write_output
############################################################
=head2 fetch_input
Description: It fetches the slice or contig according
to the input_id, and it defines the database where
the previous annotations are stored and create a
Bio::EnsEMBL::Analysis::Runnable::HavanaAdder object
for that genomic, input_id and db
Returns : Nothing
Args : None
=cut
sub fetch_input {
my ($self) = @_;
$self->throw("No input id") unless defined( $self->input_id );
$self->fetch_sequence();
# database where the ensembl genebuild genes are located
my $ensembl_db = $self->get_dbadaptor("PSEUDO_DB");
print "ENSEMBL DB: ", $ensembl_db->dbname, "\n";
# database with the Havana Vega genes to import
my $havana_db = $self->get_dbadaptor("HAVANA_DB");
print "HAVANA DB: ", $havana_db->dbname, "\n";
# Database with the CCDS models
my $ccds_db = $self->get_dbadaptor("CCDS_DB");
print "CCDS DB: ";
if ( defined($ccds_db) ) {
printf( "%s\n", $ccds_db->dbname() );
}
else {
print("(not defined)\n");
}
# Database that contains the DNA sequence
my $ref_db = $self->get_dbadaptor("REFERENCE_DB");
print $self->input_id, "\n";
my $slice = $ref_db->get_SliceAdaptor->fetch_by_name( $self->input_id );
print $slice, "\n";
$self->query($slice);
print "QUERY: ", $self->query->seq_region_name, "\n";
my $genebuilder =
new Bio::EnsEMBL::Analysis::Runnable::HavanaAdder(
'-slice' => $self->query,
'-input_id' => $self->input_id,
);
$genebuilder->ensembl_db($ensembl_db);
$genebuilder->havana_db($havana_db);
$genebuilder->ccds_db($ccds_db);
# store the object and the piece of genomic where it will run
$self->addgenebuilder( $genebuilder, $self->query );
print "I finished fetching the database adaptors\n";
} ## end sub fetch_input
############################################################
sub addgenebuilder {
my ( $self, $arg, $contig ) = @_;
if ( defined($arg) && defined($contig) ) {
$self->{_genebuilder}{ $contig->id } = $arg;
} else {
$self->throw("Wrong number of inputs [$arg,$contig]\n");
}
}
############################################################
sub get_genebuilders {
my ($self) = @_;
return $self->{_genebuilder};
}
############################################################
sub run {
my ($self) = @_;
print "Now running the analysis\n";
# get a hash, with keys = contig/slice and value = genebuilder object
my $genebuilders = $self->get_genebuilders;
print "Getting Gene adaptors again\n";
my @genes;
foreach my $region ( keys %{$genebuilders} ) {
print "Starting to get some genes\n";
my $query = $genebuilders->{$region}->query;
print "GeneBuilding for $region\n";
$genebuilders->{$region}->build_Genes;
print "Genes build now getting the final set\n";
@genes = @{ $genebuilders->{$region}->final_genes } ;
}
print "OK now I have my genes, just need to write them\n";
$self->output(@genes);
}
############################################################
# override the evil RunnableDB output method:
sub output {
my ( $self, @genes ) = @_;
unless ( $self->{_output} ) {
$self->{_output} = [];
}
if (@genes) {
push( @{ $self->{_output} }, @genes );
}
#return @{$self->{_output}};
return $self->{_output};
}
############################################################
1;
| Ensembl/ensembl-analysis | modules/Bio/EnsEMBL/Analysis/RunnableDB/HavanaAdder.pm | Perl | apache-2.0 | 7,911 |
#!/usr/bin/perl
##
# Clears an Amazon SQS queue, optionally dumping the contents to stdout.
##
use Amazon::SQS::Simple;
use Getopt::Long;
my $accesskey;
my $secretkey;
my $queuename;
my $dump = 0;
GetOptions ("accesskey=s" => \$accesskey,
"secretkey=s" => \$secretkey,
"queue=s" => \$queuename,
"dump" => \$dump);
if (defined $accesskey && defined $secretkey && defined $queuename) {
my $sqs = new Amazon::SQS::Simple($accesskey, $secretkey);
if ($sqs) {
my $queue = $sqs->GetQueue($queuename);
if ($queue) {
while(my $msg = $queue->ReceiveMessage()) {
if ($dump) {
print $msg->MessageBody(),"\n";
}
$queue->DeleteMessage($msg->ReceiptHandle());
}
}
}
}else{
print <<HELP;
Clears an SQS queue of all queued messages and optionally writes them to stdout.
Usage:
$0 --accesskey <access key> --secretkey <secret key> --queue <queue url> [--dump]
--accesskey - The Amazon account's access key
--secretkey - The Amazon account's secret access key
--queue - The absolute URL to the SQS queue
--dump - Writes each queue value to stdout
HELP
}
| krhenderson/clearsqs | clearsqs.pl | Perl | apache-2.0 | 1,257 |
#!/usr/bin/env perl
# 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.
package Script;
use strict;
use warnings;
use Carp;
use DBI;
use Getopt::Long qw/:config no_ignore_case auto_version bundling_override/;
use Pod::Usage;
sub args {
my ($self) = @_;
my $opts = { port => 3306, verbose => 0 };
GetOptions(
$opts, qw/
host|hostname|h=s
port|P=i
username|user|u=s
password|pass|p=s
databases|database|db=s@
verbose|v
log=s
help
man
/
) or pod2usage(-verbose => 1, -exitval => 1);
pod2usage(-verbose => 1, -exitval => 0) if $opts->{help};
pod2usage(-verbose => 2, -exitval => 0) if $opts->{man};
$self->{opts} = $opts;
return;
}
my $rcsid = '$Revision$';
our ($VERSION) = $rcsid =~ /(\d+\.\d+)/;
sub run {
my ($class) = @_;
my $self = bless({}, $class);
$self->args();
$self->logging();
$self->process();
if ($self->{oldfh}) {
select($self->{oldfh});
}
return;
}
sub defaults {
my ($self) = @_;
my $o = $self->opts();
foreach my $required (qw/username databases host/) {
pod2usage(-msg => sprintf('No -%s specified', $required), -verbose => 2, -exitval => 1);
}
#Processing -opt 1 -opt 2,3 into opt => [1,2,3]
$self->_cmd_line_to_array('databases') if $o->{databases};
$self->v(q{Working with %d database(s)}, scalar(@{$o->{databases}}));
return;
}
sub logging {
my ($self) = @_;
my $o = $self->opts();
if ($o->{log}) {
$o->{verbose} = 1;
my $file = $o->{log};
open my $fh, '>', $file or die "Cannot open log file '${file}' for writing: $!";
my $oldfh = select($fh);
$self->{oldfh} = $oldfh;
}
return;
}
sub process {
my ($self) = @_;
my $databases = $self->opts()->{databases};
foreach my $db (@{$databases}) {
$self->v('Working with database %s', $db);
$self->dbh($db);
$self->delete_tables();
my $ddl = sprintf('drop database %s', $db);
$self->v(qq{\tRunning: '%s'}, $ddl);
$self->dbh()->do($ddl);
$self->clear_tables();
$self->clear_dbh();
}
return;
}
sub delete_tables {
my ($self) = @_;
my @tables = keys %{ $self->tables() };
foreach my $table (@tables) {
$self->v(q{Processing '%s'}, $table);
my @sql;
if($self->is_view($table)) {
$self->v(q{'%s' is a view; just dropping}, $table);
push(@sql, 'drop view '.$table);
}
else {
$self->v(q{'%s' is being truncated and then dropped}, $table);
push(@sql,
'truncate table '.$table,
'drop table '.$table,
);
}
foreach my $statement (@sql) {
$self->v(qq{\tRunning: '%s'}, $statement);
$self->dbh()->do($statement);
}
}
return;
}
sub v {
my ($self, $msg, @args) = @_;
return unless $self->opts()->{verbose};
my $s_msg = sprintf($msg, @args);
my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) =
localtime(time());
print sprintf("[%02d-%02d-%04d %02d:%02d:%02d] %s\n",
$mday, $mon, $year + 1900,
$hour, $min, $sec, $s_msg);
return;
}
sub dbh {
my ($self, $database) = @_;
if (!exists $self->{'dbh'}) {
my $o = $self->opts();
my %args = (host => $o->{host}, port => $o->{port});
$args{database} = $database if defined $database;
my $dsn =
'DBI:mysql:' . join(q{;}, map { $_ . '=' . $args{$_} } keys %args);
$self->v('DBI connection URI %s', $dsn);
my $dbh =
DBI->connect($dsn, $o->{username}, $o->{password}, { RaiseError => 1 });
$self->{dbh} = $dbh;
}
return $self->{'dbh'};
}
sub clear_dbh {
my ($self) = @_;
if (exists $self->{dbh}) {
$self->{dbh}->disconnect();
delete $self->{dbh};
}
return;
}
sub is_view {
my ($self, $table) = @_;
return ($self->tables()->{$table} eq 'VIEW') ? 1 : 0;
}
sub tables {
my ($self) = @_;
if (!exists $self->{tables}) {
my $array =
$self->dbh()->selectcol_arrayref(
'select TABLE_NAME, TABLE_TYPE from information_schema.TABLES where TABLE_SCHEMA = DATABASE()',
{ Columns => [ 1, 2 ] }
);
my %hits = @{$array};
$self->{tables} = \%hits;
}
return $self->{tables};
}
sub clear_tables {
my ($self) = @_;
delete $self->{tables};
return;
}
sub _cmd_line_to_array {
my ($self, $key) = @_;
my $array = $self->opts()->{$key};
$array = (ref($array) && ref($array) eq 'ARRAY') ? $array : [$array];
my $string = join(q{,}, @{$array});
my @new_array = split(/,/, $string);
$self->opts()->{$key} = \@new_array;
return;
}
Script->run();
1;
__END__
=pod
=head1 NAME
remove_mysqldb.pl
=head1 SYNOPSIS
#Basic
./remove_mysqldb.pl -username USER -password PASS -host HOST [-port PORT] -database DB [-verbose] [-help | -man]
#Advanced
./remove_mysqldb.pl -username USER -password PASS -host HOST -port PORT -database DB -database DBTWO -verbose
=head1 DESCRIPTION
A script which is used to drop a database in the most lock friendly way.
If you issue a C<drop database DB> command to MySQL it first aquires
a C<LOCK_open> which is a global mutex always applied for when you open
and close a file. Once the drop command has the lock no other process can
query the MySQL DB until the lock is relinquished once the DB has been dropped.
If your DB is very large or has a large number of tables this can take a long
time and has you performing a denile of service attack on your own DB server.
=head1 OPTIONS
=over 8
=item B<--username | --user | -u>
REQUIRED. Username of the connecting account. Must be able to perform
drop and truncate calls.
=item B<--password | -pass | -p>
Password of the connecting user.
=item B<--host | --hostname | -h>
REQUIRED. Host name of the database to connect to
=item B<--port | -P>
Optional integer of the database port. Defaults to 3306
=item B<--databases | --database | --db>
Allows database name specification and can be used more than once. Comma
separated values are supported.
=item B<--verbose>
Makes the program give more information about what is going on. Otherwise
the program is silent.
=item B<--log>
If given the script will write all logs to output. Switches on C<--verbose>
=item B<--help>
Help message
=item B<--man>
Man page
=back
=head1 REQUIREMENTS
=over 8
=item Perl 5.8+
=item DBI
=item DBD::mysql
=back
=cut
| Ensembl/ensembl | misc-scripts/db/remove_mysqldb.pl | Perl | apache-2.0 | 6,952 |
=head1 LICENSE
Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
=cut
=head1 NAME
Bio::EnsEMBL::DBSQL::TranscriptAdaptor - An adaptor which performs database
interaction relating to the storage and retrieval of Transcripts
=head1 SYNOPSIS
use Bio::EnsEMBL::Registry;
Bio::EnsEMBL::Registry->load_registry_from_db(
-host => 'ensembldb.ensembl.org',
-user => 'anonymous'
);
$transcript_adaptor =
Bio::EnsEMBL::Registry->get_adaptor( 'Human', 'Core',
'Transcript' );
$transcript = $transcript_adaptor->fetch_by_dbID(1234);
$transcript =
$transcript_adaptor->fetch_by_stable_id('ENST00000201961');
$slice =
$slice_adaptor->fetch_by_region( 'Chromosome', '3', 1, 1000000 );
@transcripts = @{ $transcript_adaptor->fetch_all_by_Slice($slice) };
($transcript) =
@{ $transcript_adaptor->fetch_all_by_external_name('NP_065811.1') };
=head1 DESCRIPTION
This adaptor provides a means to retrieve and store information related
to Transcripts. Primarily this involves the retrieval or storage of
Bio::EnsEMBL::Transcript objects from a database.
See Bio::EnsEMBL::Transcript for details of the Transcript class.
=cut
package Bio::EnsEMBL::DBSQL::TranscriptAdaptor;
use strict;
use Bio::EnsEMBL::DBSQL::BaseFeatureAdaptor;
use Bio::EnsEMBL::Gene;
use Bio::EnsEMBL::Exon;
use Bio::EnsEMBL::Transcript;
use Bio::EnsEMBL::Translation;
use Bio::EnsEMBL::Utils::Exception qw( deprecate throw warning );
use vars qw(@ISA);
@ISA = qw( Bio::EnsEMBL::DBSQL::BaseFeatureAdaptor );
# _tables
#
# Description: PROTECTED implementation of superclass abstract method.
# Returns the names, aliases of the tables to use for queries.
# Returntype : list of listrefs of strings
# Exceptions : none
# Caller : internal
# Status : Stable
sub _tables {
return (
[ 'transcript', 't' ],
[ 'xref', 'x' ],
[ 'external_db', 'exdb' ] );
}
#_columns
#
# Description: PROTECTED implementation of superclass abstract method.
# Returns a list of columns to use for queries.
# Returntype : list of strings
# Exceptions : none
# Caller : internal
# Status : Stable
sub _columns {
my ($self) = @_;
my $created_date =
$self->db()->dbc()->from_date_to_seconds("created_date");
my $modified_date =
$self->db()->dbc()->from_date_to_seconds("modified_date");
my @columns =
(
't.transcript_id', 't.seq_region_id',
't.seq_region_start', 't.seq_region_end',
't.seq_region_strand', 't.analysis_id',
't.gene_id', 't.is_current',
't.stable_id', 't.version',
$created_date, $modified_date,
't.description', 't.biotype',
't.status', 'exdb.db_name',
'exdb.status', 'exdb.db_display_name',
'x.xref_id', 'x.display_label',
'x.dbprimary_acc', 'x.version',
'x.description', 'x.info_type',
'x.info_text', 'exdb.db_release'
);
$self->schema_version > 74 and push @columns, 't.source';
return @columns;
}
sub _left_join {
return (
[ 'xref', "x.xref_id = t.display_xref_id" ],
[ 'external_db', "exdb.external_db_id = x.external_db_id" ]
);
}
=head2 fetch_by_stable_id
Arg [1] : String $stable_id
The stable id of the transcript to retrieve
Example : my $tr = $tr_adaptor->fetch_by_stable_id('ENST00000309301');
Description: Retrieves a transcript via its stable id.
Returntype : Bio::EnsEMBL::Transcript
Exceptions : none
Caller : general
Status : Stable
=cut
sub fetch_by_stable_id {
my ($self, $stable_id) = @_;
my $constraint = "t.stable_id = ? AND t.is_current = 1";
$self->bind_param_generic_fetch($stable_id,SQL_VARCHAR);
my ($transcript) = @{ $self->generic_fetch($constraint) };
return $transcript;
}
sub fetch_all {
my ($self) = @_;
my $constraint = 't.biotype != "LRG_gene" and t.is_current = 1';
my @trans = @{ $self->generic_fetch($constraint) };
return \@trans ;
}
=head2 fetch_all_versions_by_stable_id
Arg [1] : String $stable_id
The stable ID of the transcript to retrieve
Example : my $tr = $tr_adaptor->fetch_all_version_by_stable_id
('ENST00000309301');
Description : Similar to fetch_by_stable_id, but retrieves all versions of a
transcript stored in the database.
Returntype : listref of Bio::EnsEMBL::Transcript objects
Exceptions : if we cant get the gene in given coord system
Caller : general
Status : At Risk
=cut
sub fetch_all_versions_by_stable_id {
my ($self, $stable_id) = @_;
my $constraint = "t.stable_id = ?";
$self->bind_param_generic_fetch($stable_id,SQL_VARCHAR);
return $self->generic_fetch($constraint);
}
=head2 fetch_by_translation_stable_id
Arg [1] : String $transl_stable_id
The stable identifier of the translation of the transcript to
retrieve
Example : my $tr = $tr_adaptor->fetch_by_translation_stable_id
('ENSP00000311007');
Description: Retrieves a Transcript object using the stable identifier of
its translation.
Returntype : Bio::EnsEMBL::Transcript
Exceptions : none
Caller : general
Status : Stable
=cut
sub fetch_by_translation_stable_id {
my ($self, $transl_stable_id ) = @_;
my $sth = $self->prepare(qq(
SELECT t.transcript_id
FROM translation tl,
transcript t
WHERE tl.stable_id = ?
AND tl.transcript_id = t.transcript_id
AND t.is_current = 1
));
$sth->bind_param(1, $transl_stable_id, SQL_VARCHAR);
$sth->execute();
my ($id) = $sth->fetchrow_array;
$sth->finish;
if ($id){
return $self->fetch_by_dbID($id);
} else {
return undef;
}
}
=head2 fetch_by_translation_id
Arg [1] : Int $id
The internal identifier of the translation whose transcript
is to be retrieved
Example : my $tr = $tr_adaptor->fetch_by_translation_id($transl->dbID);
Description: Given the internal identifier of a translation this method
retrieves the transcript associated with that translation.
If the transcript cannot be found undef is returned instead.
Returntype : Bio::EnsEMBL::Transcript or undef
Exceptions : none
Caller : general
Status : Stable
=cut
sub fetch_by_translation_id {
my ( $self, $p_dbID ) = @_;
if ( !defined($p_dbID) ) {
throw("dbID argument is required");
}
my $sth =
$self->prepare( "SELECT transcript_id "
. "FROM translation "
. "WHERE translation_id = ?" );
$sth->bind_param( 1, $p_dbID, SQL_INTEGER );
$sth->execute();
my ($dbID) = $sth->fetchrow_array();
$sth->finish();
if ($dbID) {
return $self->fetch_by_dbID($dbID);
}
return undef;
}
=head2 fetch_all_by_Gene
Arg [1] : Bio::EnsEMBL::Gene $gene
The gene to fetch transcripts of
Example : my $gene = $gene_adaptor->fetch_by_stable_id('ENSG0000123');
my @transcripts = { $tr_adaptor->fetch_all_by_Gene($gene) };
Description: Retrieves Transcript objects for given gene. Puts Genes slice
in each Transcript.
Returntype : Listref of Bio::EnsEMBL::Transcript objects
Exceptions : none
Caller : Gene->get_all_Transcripts()
Status : Stable
=cut
sub fetch_all_by_Gene {
my ( $self, $gene ) = @_;
my $constraint = "t.gene_id = " . $gene->dbID();
# Use the fetch_all_by_Slice_constraint method because it handles the
# difficult Haps/PARs and coordinate remapping.
# Get a slice that entirely overlaps the gene. This is because we
# want all transcripts to be retrieved, not just ones overlapping
# the slice the gene is on (the gene may only partially overlap the
# slice). For speed reasons, only use a different slice if necessary
# though.
my $gslice = $gene->slice();
if ( !defined($gslice) ) {
throw("Gene must have attached slice to retrieve transcripts.");
}
my $slice;
if ( $gene->start() < 1 || $gene->end() > $gslice->length() ) {
if ( $gslice->is_circular() ) {
$slice = $gslice;
} else {
$slice = $self->db->get_SliceAdaptor->fetch_by_Feature($gene);
}
} else {
$slice = $gslice;
}
my $transcripts =
$self->fetch_all_by_Slice_constraint( $slice, $constraint );
if ( $slice != $gslice ) {
my @out;
foreach my $tr ( @{$transcripts} ) {
push( @out, $tr->transfer($gslice) );
}
$transcripts = \@out;
}
my $canonical_t = $gene->canonical_transcript();
foreach my $t ( @{$transcripts} ) {
if ( $t->equals($canonical_t) ) {
$t->is_canonical(1);
last;
}
}
return $transcripts;
} ## end sub fetch_all_by_Gene
=head2 fetch_all_by_Slice
Arg [1] : Bio::EnsEMBL::Slice $slice
The slice to fetch transcripts on
Arg [2] : (optional) Boolean $load_exons
If true, exons will be loaded immediately rather than
lazy loaded later
Arg [3] : (optional) String $logic_name
The logic name of the type of features to obtain
ARG [4] : (optional) String $constraint
An extra contraint.
Example : my @transcripts = @{ $tr_adaptor->fetch_all_by_Slice($slice) };
Description: Overrides superclass method to optionally load exons
immediately rather than lazy-loading them later. This
is more efficient when there are a lot of transcripts whose
exons are going to be used.
Returntype : Listref of Bio::EnsEMBL::Transcript objects
Exceptions : thrown if exon cannot be placed on transcript slice
Caller : Slice::get_all_Transcripts
Status : Stable
=cut
sub fetch_all_by_Slice {
my ( $self, $slice, $load_exons, $logic_name, $constraint ) = @_;
my $transcripts;
if ( defined($constraint) && $constraint ne '' ) {
$transcripts = $self->SUPER::fetch_all_by_Slice_constraint( $slice,
't.is_current = 1 AND ' . $constraint, $logic_name );
} else {
$transcripts = $self->SUPER::fetch_all_by_Slice_constraint( $slice,
't.is_current = 1', $logic_name );
}
# if there are 0 or 1 transcripts still do lazy-loading
if ( !$load_exons || @$transcripts < 2 ) {
return $transcripts;
}
# preload all of the exons now, instead of lazy loading later
# faster than 1 query per transcript
# first check if the exons are already preloaded
# @todo FIXME: Should test all exons.
if ( exists( $transcripts->[0]->{'_trans_exon_array'} ) ) {
return $transcripts;
}
# get extent of region spanned by transcripts
my ($min_start, $max_end);
my $ext_slice;
unless ($slice->is_circular()) {
foreach my $t (@$transcripts) {
if (!defined($min_start) || $t->seq_region_start() < $min_start) {
$min_start = $t->seq_region_start();
}
if (!defined($max_end) || $t->seq_region_end() > $max_end) {
$max_end = $t->seq_region_end();
}
}
if ($min_start >= $slice->start() && $max_end <= $slice->end()) {
$ext_slice = $slice;
} else {
my $sa = $self->db()->get_SliceAdaptor();
$ext_slice = $sa->fetch_by_region($slice->coord_system->name(), $slice->seq_region_name(), $min_start, $max_end, $slice->strand(), $slice->coord_system->version());
}
} else {
# feature might be crossing the origin of replication (i.e. seq_region_start > seq_region_end)
# the computation of min_start|end based on seq_region_start|end is not safe
# use feature start/end relative to the slice instead
my ($min_start_feature, $max_end_feature);
foreach my $t (@$transcripts) {
if (!defined($min_start) || $t->start() < $min_start) {
$min_start = $t->start();
$min_start_feature = $t;
}
if (!defined($max_end) || $t->end() > $max_end) {
$max_end = $t->end();
$max_end_feature = $t;
}
}
# now we can reassign min_start|end to seq_region_start|end of
# the feature which spans the largest region
$min_start = $min_start_feature->seq_region_start();
$max_end = $max_end_feature->seq_region_end();
my $sa = $self->db()->get_SliceAdaptor();
$ext_slice =
$sa->fetch_by_region($slice->coord_system->name(),
$slice->seq_region_name(),
$min_start,
$max_end,
$slice->strand(),
$slice->coord_system->version());
}
# associate exon identifiers with transcripts
my %tr_hash = map { $_->dbID => $_ } @{$transcripts};
my $tr_id_str = join( ',', keys(%tr_hash) );
my $sth =
$self->prepare( "SELECT transcript_id, exon_id, rank "
. "FROM exon_transcript "
. "WHERE transcript_id IN ($tr_id_str)" );
$sth->execute();
my ( $tr_id, $ex_id, $rank );
$sth->bind_columns( \( $tr_id, $ex_id, $rank ) );
my %ex_tr_hash;
while ( $sth->fetch() ) {
$ex_tr_hash{$ex_id} ||= [];
push( @{ $ex_tr_hash{$ex_id} }, [ $tr_hash{$tr_id}, $rank ] );
}
my $ea = $self->db()->get_ExonAdaptor();
my $exons = $ea->fetch_all_by_Slice_constraint(
$ext_slice,
sprintf( "e.exon_id IN (%s)",
join( ',', sort { $a <=> $b } keys(%ex_tr_hash) ) ) );
# move exons onto transcript slice, and add them to transcripts
foreach my $ex ( @{$exons} ) {
my $new_ex;
if ( $slice != $ext_slice ) {
$new_ex = $ex->transfer($slice);
if ( !defined($new_ex) ) {
throw("Unexpected. "
. "Exon could not be transfered onto Transcript slice." );
}
} else {
$new_ex = $ex;
}
foreach my $row ( @{ $ex_tr_hash{ $new_ex->dbID() } } ) {
my ( $tr, $rank ) = @{$row};
$tr->add_Exon( $new_ex, $rank );
}
}
my $tla = $self->db()->get_TranslationAdaptor();
# load all of the translations at once
$tla->fetch_all_by_Transcript_list($transcripts);
return $transcripts;
} ## end sub fetch_all_by_Slice
=head2 fetch_all_by_external_name
Arg [1] : String $external_name
An external identifier of the transcript to be obtained
Arg [2] : (optional) String $external_db_name
The name of the external database from which the
identifier originates.
Arg [3] : Boolean override. Force SQL regex matching for users
who really do want to find all 'NM%'
Example : my @transcripts =
@{ $tr_adaptor->fetch_all_by_external_name( 'NP_065811.1') };
my @more_transcripts =
@{$tr_adaptor->fetch_all_by_external_name( 'NP_0658__._')};
Description: Retrieves all transcripts which are associated with
an external identifier such as a GO term, Swissprot
identifer, etc. Usually there will only be a single
transcript returned in the list reference, but not
always. Transcripts are returned in their native
coordinate system, i.e. the coordinate system in which
they are stored in the database. If they are required
in another coordinate system the Transcript::transfer or
Transcript::transform method can be used to convert them.
If no transcripts with the external identifier are found,
a reference to an empty list is returned.
SQL wildcards % and _ are supported in the $external_name
but their use is somewhat restricted for performance reasons.
Users that really do want % and _ in the first three characters
should use argument 3 to prevent optimisations
Returntype : listref of Bio::EnsEMBL::Transcript
Exceptions : none
Caller : general
Status : Stable
=cut
sub fetch_all_by_external_name {
my ( $self, $external_name, $external_db_name, $override) = @_;
my $entryAdaptor = $self->db->get_DBEntryAdaptor();
my @ids =
$entryAdaptor->list_transcript_ids_by_extids( $external_name,
$external_db_name, $override );
my @features = @{ $self->fetch_all_by_dbID_list( \@ids ) };
my @reference = grep { $_->slice()->is_reference() } @features;
my @non_reference = grep { ! $_->slice()->is_reference() } @features;
return [ @reference, @non_reference ];
}
=head2 fetch_all_by_GOTerm
Arg [1] : Bio::EnsEMBL::OntologyTerm
The GO term for which transcripts should be fetched.
Example: @transcripts = @{
$transcript_adaptor->fetch_all_by_GOTerm(
$go_adaptor->fetch_by_accession('GO:0030326') ) };
Description : Retrieves a list of transcripts that are
associated with the given GO term, or with any of
its descendent GO terms. The transcripts returned
are in their native coordinate system, i.e. in
the coordinate system in which they are stored
in the database. If another coordinate system
is required then the Transcript::transfer or
Transcript::transform method can be used.
Return type : listref of Bio::EnsEMBL::Transcript
Exceptions : Throws of argument is not a GO term
Caller : general
Status : Stable
=cut
sub fetch_all_by_GOTerm {
my ( $self, $term ) = @_;
assert_ref( $term, 'Bio::EnsEMBL::OntologyTerm' );
if ( $term->ontology() ne 'GO' ) {
throw('Argument is not a GO term');
}
my $entryAdaptor = $self->db->get_DBEntryAdaptor();
my %unique_dbIDs;
foreach my $accession ( map { $_->accession() }
( $term, @{ $term->descendants() } ) )
{
my @ids =
$entryAdaptor->list_transcript_ids_by_extids( $accession, 'GO' );
foreach my $dbID (@ids) { $unique_dbIDs{$dbID} = 1 }
}
my @result = @{
$self->fetch_all_by_dbID_list(
[ sort { $a <=> $b } keys(%unique_dbIDs) ]
) };
return \@result;
} ## end sub fetch_all_by_GOTerm
=head2 fetch_all_by_GOTerm_accession
Arg [1] : String
The GO term accession for which genes should be
fetched.
Example :
@genes =
@{ $gene_adaptor->fetch_all_by_GOTerm_accession(
'GO:0030326') };
Description : Retrieves a list of genes that are associated with
the given GO term, or with any of its descendent
GO terms. The genes returned are in their native
coordinate system, i.e. in the coordinate system
in which they are stored in the database. If
another coordinate system is required then the
Gene::transfer or Gene::transform method can be
used.
Return type : listref of Bio::EnsEMBL::Gene
Exceptions : Throws of argument is not a GO term accession
Caller : general
Status : Stable
=cut
sub fetch_all_by_GOTerm_accession {
my ( $self, $accession ) = @_;
if ( $accession !~ /^GO:/ ) {
throw('Argument is not a GO term accession');
}
my $goAdaptor =
Bio::EnsEMBL::Registry->get_adaptor( 'Multi', 'Ontology',
'OntologyTerm' );
my $term = $goAdaptor->fetch_by_accession($accession);
return $self->fetch_all_by_GOTerm($term);
}
=head2 fetch_by_display_label
Arg [1] : String $label - display label of transcript to fetch
Example : my $tr = $tr_adaptor->fetch_by_display_label("BRCA2");
Description: Returns the transcript which has the given display label or
undef if there is none. If there are more than 1, only the first
is reported.
Returntype : Bio::EnsEMBL::Transcript
Exceptions : none
Caller : general
Status : Stable
=cut
sub fetch_by_display_label {
my $self = shift;
my $label = shift;
my $constraint = "x.display_label = ? AND t.is_current = 1";
$self->bind_param_generic_fetch($label,SQL_VARCHAR);
my ($transcript) = @{ $self->generic_fetch($constraint) };
return $transcript;
}
=head2 fetch_all_by_exon_stable_id
Arg [1] : String $stable_id
The stable id of an exon in a transcript
Example : my $tr = $tr_adaptor->fetch_all_by_exon_stable_id
('ENSE00000309301');
Description: Retrieves a list of transcripts via an exon stable id.
Returntype : Listref of Bio::EnsEMBL::Transcript objects
Exceptions : none
Caller : general
Status : Stable
=cut
sub fetch_all_by_exon_stable_id {
my ($self, $stable_id) = @_;
my @trans ;
my $sth = $self->prepare(qq(
SELECT t.transcript_id
FROM exon_transcript et, exon e, transcript t
WHERE e.exon_id = et.exon_id
AND et.transcript_id = t.transcript_id
AND e.stable_id = ?
AND t.is_current = 1
));
$sth->bind_param(1, $stable_id, SQL_VARCHAR);
$sth->execute();
while( my $id = $sth->fetchrow_array ) {
my $transcript = $self->fetch_by_dbID($id);
push(@trans, $transcript) if $transcript;
}
if (!@trans) {
return undef;
}
return \@trans;
}
=head2 fetch_all_by_source
Arg [1] : String $source
listref of $sources
The source of the transcript to retrieve. You can have as an argument a reference
to a list of sources
Example : $transcripts = $transcript_adaptor->fetch_all_by_source('havana');
$transcripts = $transcript_adaptor->fetch_all_by_source(['ensembl', 'vega']);
Description: Retrieves an array reference of transcript objects from the database via its source or sources.
The transcript will be retrieved in its native coordinate system (i.e.
in the coordinate system it is stored in the database). It may
be converted to a different coordinate system through a call to
transform() or transfer(). If the gene or exon is not found
undef is returned instead.
Returntype : listref of Bio::EnsEMBL::Transcript
Exceptions : if we cant get the gene in given coord system
Caller : general
Status : Stable
=cut
sub fetch_all_by_source {
my ($self, $source) = @_;
my @transcripts = @{$self->generic_fetch($self->source_constraint($source))};
return \@transcripts;
}
=head2 source_constraint
Arg [1] : String $source
listref of $sources
The source of the transcript to retrieve. You can have as an argument a reference
to a list of sources
Description: Used internally to generate a SQL constraint to restrict a transcript query by source
Returntype : String
Exceptions : If source is not supplied
Caller : general
Status : Stable
=cut
sub source_constraint {
my ($self, $sources, $inline_variables) = @_;
my $constraint = "t.is_current = 1";
my $in_statement = $self->generate_in_constraint($sources, 't.source', SQL_VARCHAR, $inline_variables);
$constraint .= " and $in_statement";
return $constraint;
}
=head2 count_all_by_source
Arg [1] : String $source
listref of $source
The source of the transcript to retrieve. You can have as an argument a reference
to a list of sources
Example : $cnt = $transcript_adaptor->count_all_by_source('ensembl');
$cnt = $transcript_adaptor->count_all_by_source(['havana', 'vega']);
Description : Retrieves count of transcript objects from the database via its source or sources.
Returntype : integer
Caller : general
Status : Stable
=cut
sub count_all_by_source {
my ($self, $source) = @_;
return $self->generic_count($self->source_constraint($source));
}
=head2 count_all_by_Slice
Arg [1] : Bio::EnsEMBL::Slice $slice
The slice to count transcripts on.
Arg [2] : (optional) biotype(s) string or arrayref of strings
the biotype of the features to count.
Arg [1] : (optional) string $source
the source name of the features to count.
Example : $cnt = $transcript_adaptor->count_all_by_Slice();
Description: Method to count transcripts on a given slice, filtering by biotype and source
Returntype : integer
Exceptions : thrown if exon cannot be placed on transcript slice
Status : Stable
Caller : general
=cut
sub count_all_by_Slice {
my ($self, $slice, $biotype, $source) = @_;
my $constraint = 't.is_current = 1';
if (defined($source)) {
$constraint .= " and t.source = '$source'";
}
if (defined($biotype)) {
$constraint .= " and " . $self->biotype_constraint($biotype);
}
return $self->count_by_Slice_constraint($slice, $constraint);
}
=head2 fetch_all_by_biotype
Arg [1] : String $biotype
listref of $biotypes
The biotype of the transcript to retrieve. You can have as an argument a reference
to a list of biotypes
Example : $gene = $transcript_adaptor->fetch_all_by_biotype('protein_coding');
$gene = $transcript_adaptor->fetch_all_by_biotypes(['protein_coding', 'sRNA', 'miRNA']);
Description: Retrieves an array reference of transcript objects from the database via its biotype or biotypes.
The transcript will be retrieved in its native coordinate system (i.e.
in the coordinate system it is stored in the database). It may
be converted to a different coordinate system through a call to
transform() or transfer(). If the gene or exon is not found
undef is returned instead.
Returntype : listref of Bio::EnsEMBL::Transcript
Exceptions : if we cant get the gene in given coord system
Caller : general
Status : Stable
=cut
sub fetch_all_by_biotype {
my ($self, $biotype) = @_;
my @transcripts = @{$self->generic_fetch($self->biotype_constraint($biotype))};
return \@transcripts;
}
=head2 biotype_constraint
Arg [1] : String $biotypes
listref of $biotypes
The biotype of the transcript to retrieve. You can have as an argument a reference
to a list of biotypes
Description: Used internally to generate a SQL constraint to restrict a transcript query by biotype
Returntype : String
Exceptions : If biotype is not supplied
Caller : general
Status : Stable
=cut
sub biotype_constraint {
my ($self, $biotypes, $inline_variables) = @_;
my $constraint = "t.is_current = 1";
my $in_statement = $self->generate_in_constraint($biotypes, 't.biotype', SQL_VARCHAR, $inline_variables);
$constraint .= " and $in_statement";
return $constraint;
}
=head2 count_all_by_biotype
Arg [1] : String $biotype
listref of $biotypes
The biotype of the transcript to retrieve. You can have as an argument a reference
to a list of biotypes
Example : $cnt = $transcript_adaptor->count_all_by_biotype('protein_coding');
$cnt = $transcript_adaptor->count_all_by_biotypes(['protein_coding', 'sRNA', 'miRNA']);
Description : Retrieves count of transcript objects from the database via its biotype or biotypes.
Returntype : integer
Caller : general
Status : Stable
=cut
sub count_all_by_biotype {
my ($self, $biotype) = @_;
return $self->generic_count($self->biotype_constraint($biotype));
}
=head2 store
Arg [1] : Bio::EnsEMBL::Transcript $transcript
The transcript to be written to the database
Arg [2] : Int $gene_dbID
The identifier of the gene that this transcript is associated
with
Arg [3] : DEPRECATED (optional) Int $analysis_id
The analysis_id to use when storing this gene. This is for
backward compatibility only and used to fall back to the gene
analysis_id if no analysis object is attached to the transcript
(which you should do for new code).
Arg [4] : prevent coordinate recalculation if you are persisting
transcripts with this gene
Example : $transID = $tr_adaptor->store($transcript, $gene->dbID);
Description: Stores a transcript in the database and returns the new
internal identifier for the stored transcript.
Returntype : Int
Exceptions : none
Caller : general
Status : Stable
=cut
sub store {
my ( $self, $transcript, $gene_dbID, $analysis_id, $skip_recalculating_coordinates ) = @_;
if ( !ref($transcript)
|| !$transcript->isa('Bio::EnsEMBL::Transcript') )
{
throw("$transcript is not a EnsEMBL transcript - not storing");
}
my $db = $self->db();
if ( $transcript->is_stored($db) ) {
return $transcript->dbID();
}
# Force lazy-loading of exons and ensure coords are correct.
# If we have been told not to do this then skip doing this
# and we assume the user knows what they are doing. You have been
# warned
if(! $skip_recalculating_coordinates) {
$transcript->recalculate_coordinates();
}
my $is_current = ( defined( $transcript->is_current() )
? $transcript->is_current()
: 1 );
# store analysis
my $analysis = $transcript->analysis();
my $new_analysis_id;
if ($analysis) {
if ( $analysis->is_stored($db) ) {
$new_analysis_id = $analysis->dbID;
} else {
$new_analysis_id = $db->get_AnalysisAdaptor->store($analysis);
}
} elsif ($analysis_id) {
# Fall back to analysis passed in (usually from gene) if analysis
# wasn't set explicitely for the transcript. This is deprectated
# though.
warning( "You should explicitely attach "
. "an analysis object to the Transcript. "
. "Will fall back to Gene analysis, "
. "but this behaviour is deprecated." );
$new_analysis_id = $analysis_id;
} else {
throw("Need an analysis_id to store the Transcript.");
}
#
# Store exons - this needs to be done before the possible transfer
# of the transcript to another slice (in _prestore()). Transfering
# results in copies being made of the exons and we need to preserve
# the object identity of the exons so that they are not stored twice
# by different transcripts.
#
my $exons = $transcript->get_all_Exons();
my $exonAdaptor = $db->get_ExonAdaptor();
foreach my $exon ( @{$exons} ) {
$exonAdaptor->store($exon);
}
my $original_translation = $transcript->translation();
my $original = $transcript;
my $seq_region_id;
( $transcript, $seq_region_id ) = $self->_pre_store($transcript);
# First store the transcript without a display xref. The display xref
# needs to be set after xrefs are stored which needs to happen after
# transcript is stored.
#
# Store transcript
#
# my $store_transcript_sql =
# sprintf "INSERT INTO transcript SET gene_id = ?, analysis_id = ?, seq_region_id = ?, seq_region_start = ?, seq_region_end = ?, seq_region_strand = ?,%s biotype = ?, status = ?, description = ?, is_current = ?, canonical_translation_id = ?", ($self->schema_version > 74)?" source = ?,":'';
my @columns = qw(
gene_id
analysis_id
seq_region_id
seq_region_start
seq_region_end
seq_region_strand
);
push @columns, 'source' if ($self->schema_version > 74);
push @columns, qw(
biotype
status
description
is_current
canonical_translation_id
);
my @canned_columns;
my @canned_values;
if ( defined( $transcript->stable_id() ) ) {
push @columns, 'stable_id', 'version';
my $created = $self->db->dbc->from_seconds_to_date($transcript->created_date());
my $modified = $self->db->dbc->from_seconds_to_date($transcript->modified_date());
push @canned_columns, 'created_date', 'modified_date';
push @canned_values, $created, $modified;
}
my $columns = join(', ', @columns, @canned_columns);
my $values = join(', ', ('?') x @columns, @canned_values);
my $store_transcript_sql = qq(
INSERT INTO transcript ( $columns ) VALUES ( $values )
);
my $tst = $self->prepare($store_transcript_sql);
my $i = 0;
$tst->bind_param( ++$i, $gene_dbID, SQL_INTEGER );
$tst->bind_param( ++$i, $new_analysis_id, SQL_INTEGER );
$tst->bind_param( ++$i, $seq_region_id, SQL_INTEGER );
$tst->bind_param( ++$i, $transcript->start(), SQL_INTEGER );
$tst->bind_param( ++$i, $transcript->end(), SQL_INTEGER );
$tst->bind_param( ++$i, $transcript->strand(), SQL_TINYINT );
$self->schema_version > 74 and
$tst->bind_param( ++$i, $transcript->source(), SQL_VARCHAR );
$tst->bind_param( ++$i, $transcript->biotype(), SQL_VARCHAR );
$tst->bind_param( ++$i, $transcript->status(), SQL_VARCHAR );
$tst->bind_param( ++$i, $transcript->description(), SQL_LONGVARCHAR );
$tst->bind_param( ++$i, $is_current, SQL_TINYINT );
# If the transcript has a translation, this is updated later:
$tst->bind_param( ++$i, undef, SQL_INTEGER );
if ( defined( $transcript->stable_id() ) ) {
$tst->bind_param( ++$i, $transcript->stable_id(), SQL_VARCHAR );
my $version = ($transcript->version()) ? $transcript->version() : 1;
$tst->bind_param( ++$i, $version, SQL_INTEGER );
}
$tst->execute();
$tst->finish();
my $transc_dbID = $self->last_insert_id('transcript_id', undef, 'transcript');
#
# Store translation
#
my $alt_translations =
$transcript->get_all_alternative_translations();
my $translation = $transcript->translation();
if ( defined($translation) ) {
# Make sure that the start and end exon are set correctly.
my $start_exon = $translation->start_Exon();
my $end_exon = $translation->end_Exon();
if ( !defined($start_exon) ) {
throw("Translation does not define a start exon.");
}
if ( !defined($end_exon) ) {
throw("Translation does not defined an end exon.");
}
# If the dbID is not set, this means the exon must have been a
# different object in memory than the the exons of the transcript.
# Try to find the matching exon in all of the exons we just stored.
if ( !defined( $start_exon->dbID() ) ) {
my $key = $start_exon->hashkey();
($start_exon) = grep { $_->hashkey() eq $key } @$exons;
if ( defined($start_exon) ) {
$translation->start_Exon($start_exon);
} else {
throw( "Translation's start_Exon does not appear "
. "to be one of the exons in "
. "its associated Transcript" );
}
}
if ( !defined( $end_exon->dbID() ) ) {
my $key = $end_exon->hashkey();
($end_exon) = grep { $_->hashkey() eq $key } @$exons;
if ( defined($end_exon) ) {
$translation->end_Exon($end_exon);
} else {
throw( "Translation's end_Exon does not appear "
. "to be one of the exons in "
. "its associated Transcript." );
}
}
my $old_dbid = $translation->dbID();
$db->get_TranslationAdaptor()->store( $translation, $transc_dbID );
# Need to update the canonical_translation_id for this transcript.
my $sth = $self->prepare(
q(
UPDATE transcript
SET canonical_translation_id = ?
WHERE transcript_id = ?)
);
$sth->bind_param( 1, $translation->dbID(), SQL_INTEGER );
$sth->bind_param( 2, $transc_dbID, SQL_INTEGER );
$sth->execute();
# Set values of the original translation, we may have copied it when
# we transformed the transcript.
$original_translation->dbID( $translation->dbID() );
$original_translation->adaptor( $translation->adaptor() );
} ## end if ( defined($translation...))
#
# Store the alternative translations, if there are any.
#
if ( defined($alt_translations)
&& scalar( @{$alt_translations} ) > 0 )
{
foreach my $alt_translation ( @{$alt_translations} ) {
my $start_exon = $alt_translation->start_Exon();
my $end_exon = $alt_translation->end_Exon();
if ( !defined($start_exon) ) {
throw("Translation does not define a start exon.");
} elsif ( !defined($end_exon) ) {
throw("Translation does not defined an end exon.");
}
if ( !defined( $start_exon->dbID() ) ) {
my $key = $start_exon->hashkey();
($start_exon) = grep { $_->hashkey() eq $key } @{$exons};
if ( defined($start_exon) ) {
$alt_translation->start_Exon($start_exon);
} else {
throw( "Translation's start_Exon does not appear "
. "to be one of the exon in"
. "its associated Transcript" );
}
}
if ( !defined( $end_exon->dbID() ) ) {
my $key = $end_exon->hashkey();
($end_exon) = grep { $_->hashkey() eq $key } @$exons;
if ( defined($end_exon) ) {
$alt_translation->end_Exon($end_exon);
} else {
throw( "Translation's end_Exon does not appear "
. "to be one of the exons in "
. "its associated Transcript." );
}
}
$db->get_TranslationAdaptor()
->store( $alt_translation, $transc_dbID );
} ## end foreach my $alt_translation...
} ## end if ( defined($alt_translations...))
#
# Store the xrefs/object xref mapping.
#
my $dbEntryAdaptor = $db->get_DBEntryAdaptor();
foreach my $dbe ( @{ $transcript->get_all_DBEntries() } ) {
$dbEntryAdaptor->store( $dbe, $transc_dbID, "Transcript", 1 );
}
#
# Update transcript to point to display xref if it is set.
#
if ( my $dxref = $transcript->display_xref() ) {
my $dxref_id;
if ( $dxref->is_stored($db) ) {
$dxref_id = $dxref->dbID();
} else {
$dxref_id = $dbEntryAdaptor->exists($dxref);
}
if ( defined($dxref_id) ) {
my $sth =
$self->prepare( "UPDATE transcript "
. "SET display_xref_id = ? "
. "WHERE transcript_id = ?" );
$sth->bind_param( 1, $dxref_id, SQL_INTEGER );
$sth->bind_param( 2, $transc_dbID, SQL_INTEGER );
$sth->execute();
$dxref->dbID($dxref_id);
$dxref->adaptor($dbEntryAdaptor);
$sth->finish();
} else {
warning(sprintf(
"Display_xref %s:%s is not stored in database.\n"
. "Not storing relationship to this transcript.",
$dxref->dbname(), $dxref->display_id() ) );
$dxref->dbID(undef);
$dxref->adaptor(undef);
}
} ## end if ( my $dxref = $transcript...)
#
# Link transcript to exons in exon_transcript table
#
my $etst = $self->prepare(
"INSERT INTO exon_transcript (exon_id,transcript_id,rank) "
. "VALUES (?,?,?)" );
my $rank = 1;
foreach my $exon ( @{ $transcript->get_all_Exons } ) {
$etst->bind_param( 1, $exon->dbID, SQL_INTEGER );
$etst->bind_param( 2, $transc_dbID, SQL_INTEGER );
$etst->bind_param( 3, $rank, SQL_INTEGER );
$etst->execute();
$rank++;
}
$etst->finish();
# Now the supporting evidence
my $tsf_adaptor = $db->get_TranscriptSupportingFeatureAdaptor();
$tsf_adaptor->store( $transc_dbID,
$transcript->get_all_supporting_features() );
# store transcript attributes if there are any
my $attr_adaptor = $db->get_AttributeAdaptor();
$attr_adaptor->store_on_Transcript( $transc_dbID,
$transcript->get_all_Attributes() );
# store the IntronSupportingEvidence features
my $ise_adaptor = $db->get_IntronSupportingEvidenceAdaptor();
my $intron_supporting_evidence = $transcript->get_all_IntronSupportingEvidence();
foreach my $ise (@{$intron_supporting_evidence}) {
$ise_adaptor->store($ise);
$ise_adaptor->store_transcript_linkage($ise, $transcript, $transc_dbID);
}
# Update the original transcript object - not the transfered copy that
# we might have created.
$original->dbID($transc_dbID);
$original->adaptor($self);
return $transc_dbID;
} ## end sub store
=head2 get_Interpro_by_transid
Arg [1] : String $trans_stable_id
The stable if of the transcript to obtain
Example : @i = $tr_adaptor->get_Interpro_by_transid($trans->stable_id());
Description: Gets interpro accession numbers by transcript stable id.
A hack really - we should have a much more structured
system than this.
Returntype : listref of strings (Interpro_acc:description)
Exceptions : none
Caller : domainview? , GeneView
Status : Stable
=cut
sub get_Interpro_by_transid {
my ($self,$trans_stable_id) = @_;
my $straight_join = $self->_can_straight_join ? 'STRAIGHT_JOIN' : '';
my $sth = $self->prepare(qq(
SELECT ${straight_join} i.interpro_ac, x.description
FROM transcript t,
translation tl,
protein_feature pf,
interpro i,
xref x
WHERE t.stable_id = ?
AND tl.transcript_id = t.transcript_id
AND tl.translation_id = pf.translation_id
AND i.id = pf.hit_name
AND i.interpro_ac = x.dbprimary_acc
AND t.is_current = 1
));
$sth->bind_param(1, $trans_stable_id, SQL_VARCHAR);
$sth->execute();
my @out;
my %h;
while( (my $arr = $sth->fetchrow_arrayref()) ) {
if( $h{$arr->[0]} ) { next; }
$h{$arr->[0]}=1;
my $string = $arr->[0] .":".$arr->[1];
push(@out,$string);
}
return \@out;
}
=head2 is_Transcript_canonical()
Arg [1] : Bio::EnsEMBL::Transcript $transcript
The transcript to query with
Example : $tr_adaptor->is_Transcript_canonical($transcript);
Description : Returns a boolean if the given transcript is considered
canonical with respect to a gene
Returntype : Boolean
Exceptions : None
Caller : Bio::EnsEMBL::Transcript
Status : Beta
=cut
sub is_Transcript_canonical {
my ($self, $transcript) = @_;
return $self->dbc()->sql_helper()->execute_single_result(
-SQL => 'select count(*) from gene where canonical_transcript_id =?',
-PARAMS => [$transcript->dbID()]
);
}
=head2 remove
Arg [1] : Bio::EnsEMBL::Transcript $transcript
The transcript to remove from the database
Example : $tr_adaptor->remove($transcript);
Description: Removes a transcript completely from the database, and all
associated information.
This method is usually called by the GeneAdaptor::remove method
because this method will not preform the removal of genes
which are associated with this transcript. Do not call this
method directly unless you know there are no genes associated
with the transcript!
Returntype : none
Exceptions : throw on incorrect arguments
warning if transcript is not in this database
Caller : GeneAdaptor::remove
Status : Stable
=cut
sub remove {
my $self = shift;
my $transcript = shift;
if(!ref($transcript) || !$transcript->isa('Bio::EnsEMBL::Transcript')) {
throw("Bio::EnsEMBL::Transcript argument expected");
}
# sanity check: make sure nobody tries to slip past a prediction transcript
# which inherits from transcript but actually uses different tables
if($transcript->isa('Bio::EnsEMBL::PredictionTranscript')) {
throw("TranscriptAdaptor can only remove Transcripts " .
"not PredictionTranscripts");
}
if ( !$transcript->is_stored($self->db()) ) {
warning("Cannot remove transcript ". $transcript->dbID .". Is not stored ".
"in this database.");
return;
}
# remove the supporting features of this transcript
my $prot_adp = $self->db->get_ProteinAlignFeatureAdaptor;
my $dna_adp = $self->db->get_DnaAlignFeatureAdaptor;
my $sfsth = $self->prepare("SELECT feature_type, feature_id " .
"FROM transcript_supporting_feature " .
"WHERE transcript_id = ?");
$sfsth->bind_param(1, $transcript->dbID, SQL_INTEGER);
$sfsth->execute();
# statements to check for shared align_features
my $sth1 = $self->prepare("SELECT count(*) FROM supporting_feature " .
"WHERE feature_type = ? AND feature_id = ?");
my $sth2 = $self->prepare("SELECT count(*) " .
"FROM transcript_supporting_feature " .
"WHERE feature_type = ? AND feature_id = ?");
SUPPORTING_FEATURE:
while(my ($type, $feature_id) = $sfsth->fetchrow()){
# only remove align_feature if this is the last reference to it
$sth1->bind_param(1, $type, SQL_VARCHAR);
$sth1->bind_param(2, $feature_id, SQL_INTEGER);
$sth1->execute;
$sth2->bind_param(1, $type, SQL_VARCHAR);
$sth2->bind_param(2, $feature_id, SQL_INTEGER);
$sth2->execute;
my ($count1) = $sth1->fetchrow;
my ($count2) = $sth2->fetchrow;
if ($count1 + $count2 > 1) {
#warn "transcript: shared feature, not removing $type|$feature_id\n";
next SUPPORTING_FEATURE;
}
#warn "transcript: removing $type|$feature_id\n";
if($type eq 'protein_align_feature'){
my $f = $prot_adp->fetch_by_dbID($feature_id);
$prot_adp->remove($f);
}
elsif($type eq 'dna_align_feature'){
my $f = $dna_adp->fetch_by_dbID($feature_id);
$dna_adp->remove($f);
}
else {
warning("Unknown supporting feature type $type. Not removing feature.");
}
}
$sfsth->finish();
$sth1->finish();
$sth2->finish();
# delete the association to supporting features
$sfsth = $self->prepare("DELETE FROM transcript_supporting_feature WHERE transcript_id = ?");
$sfsth->bind_param(1, $transcript->dbID, SQL_INTEGER);
$sfsth->execute();
$sfsth->finish();
# delete the associated IntronSupportingEvidence and if the ISE had no more
# linked transcripts remove it
my $ise_adaptor = $self->db->get_IntronSupportingEvidenceAdaptor();
foreach my $ise (@{$transcript->get_all_IntronSupportingEvidence()}) {
$ise_adaptor->remove_transcript_linkage($ise, $transcript);
if(! $ise->has_linked_transcripts()) {
$ise_adaptor->remove($ise);
}
}
# remove all xref linkages to this transcript
my $dbeAdaptor = $self->db->get_DBEntryAdaptor();
foreach my $dbe (@{$transcript->get_all_DBEntries}) {
$dbeAdaptor->remove_from_object($dbe, $transcript, 'Transcript');
}
# remove the attributes associated with this transcript
my $attrib_adp = $self->db->get_AttributeAdaptor;
$attrib_adp->remove_from_Transcript($transcript);
# remove the translation associated with this transcript
my $translationAdaptor = $self->db->get_TranslationAdaptor();
if( defined($transcript->translation()) ) {
$translationAdaptor->remove( $transcript->translation );
}
# remove exon associations to this transcript
my $exonAdaptor = $self->db->get_ExonAdaptor();
foreach my $exon ( @{$transcript->get_all_Exons()} ) {
# get the number of transcript references to this exon
# only remove the exon if this is the last transcript to
# reference it
my $sth = $self->prepare( "SELECT count(*)
FROM exon_transcript
WHERE exon_id = ?" );
$sth->bind_param(1, $exon->dbID, SQL_INTEGER);
$sth->execute();
my ($count) = $sth->fetchrow_array();
$sth->finish();
if($count == 1){
$exonAdaptor->remove( $exon );
}
}
my $sth = $self->prepare( "DELETE FROM exon_transcript
WHERE transcript_id = ?" );
$sth->bind_param(1, $transcript->dbID, SQL_INTEGER);
$sth->execute();
$sth->finish();
$sth = $self->prepare( "DELETE FROM transcript
WHERE transcript_id = ?" );
$sth->bind_param(1, $transcript->dbID, SQL_INTEGER);
$sth->execute();
$sth->finish();
$transcript->dbID(undef);
$transcript->adaptor(undef);
return;
}
=head2 update
Arg [1] : Bio::EnsEMBL::Transcript $transcript
The transcript to update
Example : $tr_adaptor->update($transcript);
Description: Updates a transcript in the database.
Returntype : None
Exceptions : thrown if the $transcript is not a Bio::EnsEMBL::Transcript.
warn if the method is called on a transcript that does not exist
in the database.
Should warn if trying to update the number of attached exons, but
this is a far more complex process and is not yet implemented.
Caller : general
Status : Stable
=cut
sub update {
my ( $self, $transcript ) = @_;
if ( !defined($transcript)
|| !ref($transcript)
|| !$transcript->isa('Bio::EnsEMBL::Transcript') )
{
throw("Must update a transcript object, not a $transcript");
}
my $update_transcript_sql =
sprintf "UPDATE transcript SET analysis_id = ?, display_xref_id = ?, description = ?,%s biotype = ?, status = ?, is_current = ?, canonical_translation_id = ? WHERE transcript_id = ?", ($self->schema_version > 74)?" source = ?,":'';
my $display_xref = $transcript->display_xref();
my $display_xref_id;
if ( defined($display_xref) && $display_xref->dbID() ) {
$display_xref_id = $display_xref->dbID();
} else {
$display_xref_id = undef;
}
my $sth = $self->prepare($update_transcript_sql);
my $i = 0;
$sth->bind_param( ++$i, $transcript->analysis()->dbID(), SQL_INTEGER );
$sth->bind_param( ++$i, $display_xref_id, SQL_INTEGER );
$sth->bind_param( ++$i, $transcript->description(), SQL_LONGVARCHAR );
$self->schema_version > 74 and
$sth->bind_param( ++$i, $transcript->source(), SQL_VARCHAR );
$sth->bind_param( ++$i, $transcript->biotype(), SQL_VARCHAR );
$sth->bind_param( ++$i, $transcript->status(), SQL_VARCHAR );
$sth->bind_param( ++$i, $transcript->is_current(), SQL_TINYINT );
$sth->bind_param( ++$i, (
defined( $transcript->translation() )
? $transcript->translation()->dbID()
: undef ),
SQL_INTEGER );
$sth->bind_param( ++$i, $transcript->dbID(), SQL_INTEGER );
$sth->execute();
} ## end sub update
=head2 list_dbIDs
Example : @transcript_ids = @{ $t_adaptor->list_dbIDs };
Description: Gets a list of internal ids for all transcripts in the db.
Arg[1] : <optional> int. not 0 for the ids to be sorted by the seq_region. Returntype : Listref of Ints
Exceptions : none
Caller : general
Status : Stable
=cut
sub list_dbIDs {
my ($self, $ordered) = @_;
return $self->_list_dbIDs("transcript",undef, $ordered);
}
=head2 list_stable_ids
Example : @stable_trans_ids = @{ $transcript_adaptor->list_stable_ids };
Description: Gets a list of stable ids for all transcripts in the current
database.
Returntype : Listref of Strings
Exceptions : none
Caller : general
Status : Stable
=cut
sub list_stable_ids {
my ($self) = @_;
return $self->_list_dbIDs("transcript", "stable_id");
}
#_objs_from_sth
# Arg [1] : StatementHandle $sth
# Arg [2] : Bio::EnsEMBL::AssemblyMapper $mapper
# Arg [3] : Bio::EnsEMBL::Slice $dest_slice
# Description: PROTECTED implementation of abstract superclass method.
# Responsible for the creation of Transcripts.
# Returntype : Listref of Bio::EnsEMBL::Transcripts in target coord system
# Exceptions : none
# Caller : internal
# Status : Stable
sub _objs_from_sth {
my ($self, $sth, $mapper, $dest_slice) = @_;
#
# This code is ugly because an attempt has been made to remove as many
# function calls as possible for speed purposes. Thus many caches and
# a fair bit of gymnastics is used.
#
my $sa = $self->db()->get_SliceAdaptor();
my $aa = $self->db()->get_AnalysisAdaptor();
my $dbEntryAdaptor = $self->db()->get_DBEntryAdaptor();
my @transcripts;
my %analysis_hash;
my %slice_hash;
my %sr_name_hash;
my %sr_cs_hash;
my (
$transcript_id, $seq_region_id, $seq_region_start,
$seq_region_end, $seq_region_strand, $analysis_id,
$gene_id, $is_current, $stable_id,
$version, $created_date, $modified_date,
$description, $biotype, $status,
$external_db, $external_status, $external_db_name,
$display_xref_id, $xref_display_label, $xref_primary_acc,
$xref_version, $xref_description, $xref_info_type,
$xref_info_text, $external_release, $source
);
if ($self->schema_version() > 74) {
$sth->bind_columns(
\(
$transcript_id, $seq_region_id, $seq_region_start,
$seq_region_end, $seq_region_strand, $analysis_id,
$gene_id, $is_current, $stable_id,
$version, $created_date, $modified_date,
$description, $biotype, $status,
$external_db, $external_status, $external_db_name,
$display_xref_id, $xref_display_label, $xref_primary_acc,
$xref_version, $xref_description, $xref_info_type,
$xref_info_text, $external_release, $source
) );
} else {
$sth->bind_columns(
\(
$transcript_id, $seq_region_id, $seq_region_start,
$seq_region_end, $seq_region_strand, $analysis_id,
$gene_id, $is_current, $stable_id,
$version, $created_date, $modified_date,
$description, $biotype, $status,
$external_db, $external_status, $external_db_name,
$display_xref_id, $xref_display_label, $xref_primary_acc,
$xref_version, $xref_description, $xref_info_type,
$xref_info_text, $external_release
) );
}
my $dest_slice_start;
my $dest_slice_end;
my $dest_slice_strand;
my $dest_slice_length;
my $dest_slice_cs;
my $dest_slice_sr_name;
my $dest_slice_sr_id;
my $asma;
if ($dest_slice) {
$dest_slice_start = $dest_slice->start();
$dest_slice_end = $dest_slice->end();
$dest_slice_strand = $dest_slice->strand();
$dest_slice_length = $dest_slice->length();
$dest_slice_cs = $dest_slice->coord_system();
$dest_slice_sr_name = $dest_slice->seq_region_name();
$dest_slice_sr_id = $dest_slice->get_seq_region_id();
$asma = $self->db->get_AssemblyMapperAdaptor();
}
FEATURE: while($sth->fetch()) {
#get the analysis object
my $analysis = $analysis_hash{$analysis_id} ||= $aa->fetch_by_dbID($analysis_id);
$analysis_hash{$analysis_id} = $analysis;
#need to get the internal_seq_region, if present
$seq_region_id = $self->get_seq_region_id_internal($seq_region_id);
my $slice = $slice_hash{"ID:".$seq_region_id};
if (!$slice) {
$slice = $sa->fetch_by_seq_region_id($seq_region_id);
$slice_hash{"ID:".$seq_region_id} = $slice;
$sr_name_hash{$seq_region_id} = $slice->seq_region_name();
$sr_cs_hash{$seq_region_id} = $slice->coord_system();
}
#obtain a mapper if none was defined, but a dest_seq_region was
if(!$mapper && $dest_slice && !$dest_slice_cs->equals($slice->coord_system)) {
$mapper = $asma->fetch_by_CoordSystems($dest_slice_cs, $slice->coord_system);
}
my $sr_name = $sr_name_hash{$seq_region_id};
my $sr_cs = $sr_cs_hash{$seq_region_id};
#
# remap the feature coordinates to another coord system
# if a mapper was provided
#
if ($mapper) {
if (defined $dest_slice && $mapper->isa('Bio::EnsEMBL::ChainedAssemblyMapper') ) {
($seq_region_id, $seq_region_start, $seq_region_end, $seq_region_strand) =
$mapper->map($sr_name, $seq_region_start, $seq_region_end, $seq_region_strand, $sr_cs, 1, $dest_slice);
} else {
($seq_region_id, $seq_region_start, $seq_region_end, $seq_region_strand) =
$mapper->fastmap($sr_name, $seq_region_start, $seq_region_end, $seq_region_strand, $sr_cs);
}
#skip features that map to gaps or coord system boundaries
next FEATURE if (!defined($seq_region_id));
#get a slice in the coord system we just mapped to
$slice = $slice_hash{"ID:".$seq_region_id} ||= $sa->fetch_by_seq_region_id($seq_region_id);
}
#
# If a destination slice was provided convert the coords.
#
if (defined($dest_slice)) {
my $seq_region_len = $dest_slice->seq_region_length();
if ( $dest_slice_strand == 1 ) {
$seq_region_start = $seq_region_start - $dest_slice_start + 1;
$seq_region_end = $seq_region_end - $dest_slice_start + 1;
if ( $dest_slice->is_circular ) {
# Handle circular chromosomes.
if ( $seq_region_start > $seq_region_end ) {
# Looking at a feature overlapping the chromosome origin.
if ( $seq_region_end > $dest_slice_start ) {
# Looking at the region in the beginning of the chromosome
$seq_region_start -= $seq_region_len;
}
if ( $seq_region_end < 0 ) {
$seq_region_end += $seq_region_len;
}
} else {
if ($dest_slice_start > $dest_slice_end && $seq_region_end < 0) {
# Looking at the region overlapping the chromosome
# origin and a feature which is at the beginning of the
# chromosome.
$seq_region_start += $seq_region_len;
$seq_region_end += $seq_region_len;
}
}
}
} else {
my $start = $dest_slice_end - $seq_region_end + 1;
my $end = $dest_slice_end - $seq_region_start + 1;
if ($dest_slice->is_circular()) {
if ($dest_slice_start > $dest_slice_end) {
# slice spans origin or replication
if ($seq_region_start >= $dest_slice_start) {
$end += $seq_region_len;
$start += $seq_region_len if $seq_region_end > $dest_slice_start;
} elsif ($seq_region_start <= $dest_slice_end) {
# do nothing
} elsif ($seq_region_end >= $dest_slice_start) {
$start += $seq_region_len;
$end += $seq_region_len;
} elsif ($seq_region_end <= $dest_slice_end) {
$end += $seq_region_len if $end < 0;
} elsif ($seq_region_start > $seq_region_end) {
$end += $seq_region_len;
}
} else {
if ($seq_region_start <= $dest_slice_end and $seq_region_end >= $dest_slice_start) {
# do nothing
} elsif ($seq_region_start > $seq_region_end) {
if ($seq_region_start <= $dest_slice_end) {
$start -= $seq_region_len;
} elsif ($seq_region_end >= $dest_slice_start) {
$end += $seq_region_len;
}
}
}
}
$seq_region_start = $start;
$seq_region_end = $end;
$seq_region_strand *= -1;
} ## end else [ if ( $dest_slice_strand...)]
# Throw away features off the end of the requested slice or on
# different seq_region.
if ($seq_region_end < 1
|| $seq_region_start > $dest_slice_length
|| ($dest_slice_sr_id != $seq_region_id)) {
next FEATURE;
}
$slice = $dest_slice;
}
my $display_xref;
if ($display_xref_id) {
$display_xref = Bio::EnsEMBL::DBEntry->new_fast( {
'dbID' => $display_xref_id,
'adaptor' => $dbEntryAdaptor,
'display_id' => $xref_display_label,
'primary_id' => $xref_primary_acc,
'version' => $xref_version,
'description' => $xref_description,
'release' => $external_release,
'dbname' => $external_db,
'db_display_name' => $external_db_name,
'info_type' => $xref_info_type,
'info_text' => $xref_info_text
});
$display_xref->status($external_status);
}
# Finally, create the new Transcript.
my $params =
{
'analysis' => $analysis,
'biotype' => $biotype,
'start' => $seq_region_start,
'end' => $seq_region_end,
'strand' => $seq_region_strand,
'adaptor' => $self,
'slice' => $slice,
'dbID' => $transcript_id,
'stable_id' => $stable_id,
'version' => $version,
'created_date' => $created_date || undef,
'modified_date' => $modified_date || undef,
'description' => $description,
'external_name' => $xref_display_label,
'external_status' => $external_status,
'external_display_name' => $external_db_name,
'external_db' => $external_db,
'external_status' => $external_status,
'display_xref' => $display_xref,
'status' => $status,
'is_current' => $is_current,
'edits_enabled' => 1
};
$self->schema_version > 74 and $params->{'source'} = $source;
push( @transcripts,
$self->_create_feature_fast(
'Bio::EnsEMBL::Transcript',$params) );
}
return \@transcripts;
}
=head2 fetch_all_by_exon_supporting_evidence
Arg [1] : String $hit_name
Name of supporting feature
Arg [2] : String $feature_type
one of "dna_align_feature" or "protein_align_feature"
Arg [3] : (optional) Bio::Ensembl::Analysis
Example : $tr = $tr_adaptor->fetch_all_by_exon_supporting_evidence
('XYZ', 'dna_align_feature');
Description: Gets all the transcripts with exons which have a specified hit
on a particular type of feature. Optionally filter by analysis.
Returntype : Listref of Bio::EnsEMBL::Transcript objects
Exceptions : If feature_type is not of correct type.
Caller : general
Status : Stable
=cut
sub fetch_all_by_exon_supporting_evidence {
my ($self, $hit_name, $feature_type, $analysis) = @_;
if($feature_type !~ /(dna)|(protein)_align_feature/) {
throw("feature type must be dna_align_feature or protein_align_feature");
}
my $anal_from = "";
$anal_from = ", analysis a " if ($analysis);
my $anal_where = "";
$anal_where = "AND a.analysis_id = f.analysis_id AND a.analysis_id=? "
if ($analysis);
my $sql = qq(
SELECT DISTINCT(t.transcript_id)
FROM transcript t,
exon_transcript et,
supporting_feature sf,
$feature_type f
$anal_from
WHERE t.transcript_id = et.transcript_id
AND t.is_current = 1
AND et.exon_id = sf.exon_id
AND sf.feature_id = f.${feature_type}_id
AND sf.feature_type = ?
AND f.hit_name=?
$anal_where
);
my $sth = $self->prepare($sql);
$sth->bind_param(1, $feature_type, SQL_VARCHAR);
$sth->bind_param(2, $hit_name, SQL_VARCHAR);
$sth->bind_param(3, $analysis->dbID(), SQL_INTEGER) if ($analysis);
$sth->execute();
my @transcripts;
while( my $id = $sth->fetchrow_array ) {
my $transcript = $self->fetch_by_dbID( $id );
push(@transcripts, $transcript) if $transcript;
}
return \@transcripts;
}
=head2 fetch_all_by_transcript_supporting_evidence
Arg [1] : String $hit_name
Name of supporting feature
Arg [2] : String $feature_type
one of "dna_align_feature" or "protein_align_feature"
Arg [3] : (optional) Bio::Ensembl::Analysis
Example : $transcripts = $transcript_adaptor->fetch_all_by_transcript_supporting_evidence('XYZ', 'dna_align_feature');
Description: Gets all the transcripts with evidence from a specified hit_name on a particular type of feature, stored in the
transcript_supporting_feature table. Optionally filter by analysis. For hits stored in the supporting_feature
table (linked to exons) use fetch_all_by_exon_supporting_evidence instead.
Returntype : Listref of Bio::EnsEMBL::Transcript objects
Exceptions : If feature_type is not of correct type.
Caller : general
Status : Stable
=cut
sub fetch_all_by_transcript_supporting_evidence {
my ($self, $hit_name, $feature_type, $analysis) = @_;
if($feature_type !~ /(dna)|(protein)_align_feature/) {
throw("feature type must be dna_align_feature or protein_align_feature");
}
my $anal_from = "";
$anal_from = ", analysis a " if ($analysis);
my $anal_where = "";
$anal_where = "AND a.analysis_id = f.analysis_id AND a.analysis_id=? "
if ($analysis);
my $sql = qq(
SELECT DISTINCT(t.transcript_id)
FROM transcript t,
transcript_supporting_feature sf,
$feature_type f
$anal_from
WHERE t.transcript_id = sf.transcript_id
AND t.is_current = 1
AND sf.feature_id = f.${feature_type}_id
AND sf.feature_type = ?
AND f.hit_name=?
$anal_where
);
my $sth = $self->prepare($sql);
$sth->bind_param(1, $feature_type, SQL_VARCHAR);
$sth->bind_param(2, $hit_name, SQL_VARCHAR);
$sth->bind_param(3, $analysis->dbID(), SQL_INTEGER) if ($analysis);
$sth->execute();
my @transcripts;
while( my $id = $sth->fetchrow_array ) {
my $transcript = $self->fetch_by_dbID( $id );
push(@transcripts, $transcript) if $transcript;
}
return \@transcripts;
}
##########################
# #
# DEPRECATED METHODS #
# #
##########################
=head2 get_display_xref
Description: DEPRECATED. Use $transcript->display_xref() instead.
=cut
sub get_display_xref {
my ($self, $transcript) = @_;
deprecate("display_xref should be retreived from Transcript object directly.");
if ( !defined $transcript ) {
throw("Must call with a Transcript object");
}
my $sth = $self->prepare(qq(
SELECT e.db_name,
x.display_label,
e.db_external_name,
x.xref_id
FROM transcript t,
xref x,
external_db e
WHERE t.transcript_id = ?
AND t.display_xref_id = x.xref_id
AND x.external_db_id = e.external_db_id
));
$sth->bind_param(1, $transcript->dbID, SQL_INTEGER);
$sth->execute();
my ($db_name, $display_label, $xref_id, $display_db_name ) =
$sth->fetchrow_array();
if ( !defined $xref_id ) {
return undef;
}
my $db_entry = Bio::EnsEMBL::DBEntry->new(
-dbid => $xref_id,
-adaptor => $self->db->get_DBEntryAdaptor(),
-dbname => $db_name,
-display_id => $display_label
-db_display_name => $display_db_name
);
return $db_entry;
}
=head2 get_stable_entry_info
Description: DEPRECATED. Use $transcript->stable_id() instead.
=cut
sub get_stable_entry_info {
my ($self, $transcript) = @_;
deprecate("Stable ids should be loaded directly now");
unless ( defined $transcript && ref $transcript &&
$transcript->isa('Bio::EnsEMBL::Transcript') ) {
throw("Needs a Transcript object, not a $transcript");
}
my $sth = $self->prepare(qq(
SELECT stable_id, version
FROM transcript
WHERE transcript_id = ?
));
$sth->bind_param(1, $transcript->dbID, SQL_INTEGER);
$sth->execute();
my @array = $sth->fetchrow_array();
$transcript->{'_stable_id'} = $array[0];
$transcript->{'_version'} = $array[1];
return 1;
}
=head2 fetch_all_by_DBEntry
Description: DEPRECATED. Use fetch_all_by_external_name() instead.
=cut
sub fetch_all_by_DBEntry {
my $self = shift;
deprecate('Use fetch_all_by_external_name instead.');
return $self->fetch_all_by_external_name(@_);
}
1;
| willmclaren/ensembl | modules/Bio/EnsEMBL/DBSQL/TranscriptAdaptor.pm | Perl | apache-2.0 | 69,219 |
#!/usr/bin/perl
# Wiki: https://www.loxwiki.eu/display/LOXBERRY/LoxBerry%3A%3AIO%3A%3Amshttp_call
use LoxBerry::IO;
$LoxBerry::IO::DEBUG = 1;
my $value = LoxBerry::IO::mshttp_get( 1, "Heizraumlicht" );
print "Value: $value\n";
my $value = LoxBerry::IO::mshttp_get( 1, "SSUG-Netzteil-24V" );
print "Value: $value\n";
my $value = LoxBerry::IO::mshttp_get( 1, "Betrieb Zeit seit Aufzeichnung" );
print "Value: $value\n";
| mschlenstedt/Loxberry | libs/perllib/LoxBerry/testing/mshttp_get.pl | Perl | apache-2.0 | 432 |
package Sisimai::MTA::Postfix;
use parent 'Sisimai::MTA';
use feature ':5.10';
use strict;
use warnings;
# Postfix manual - bounce(5) - http://www.postfix.org/bounce.5.html
my $RxMTA = {
'from' => qr/ [(]Mail Delivery System[)]\z/,
'begin' => [
qr/\A\s+The Postfix program\z/,
qr/\A\s+The Postfix on .+ program\z/, # The Postfix on <os name> program
qr/\A\s+The \w+ Postfix program\z/, # The <name> Postfix program
qr/\A\s+The mail system\z/,
qr/\AThe \w+ program\z/, # The <custmized-name> program
qr/\AThis is the Postfix program/,
qr/\AThis is the \w+ Postfix program/, # This is the <name> Postfix program
qr/\AThis is the \w+ program/, # This is the <customized-name> Postfix program
qr/\AThis is the mail system at host/, # This is the mail system at host <hostname>.
],
'rfc822' => [
qr|\AContent-Type: message/rfc822\z|,
qr|\AContent-Type: text/rfc822-headers\z|,
],
'endof' => qr/\A__END_OF_EMAIL_MESSAGE__\z/,
'subject' => qr/\AUndelivered Mail Returned to Sender\z/,
};
sub version { '4.0.8' }
sub description { 'Postfix' }
sub smtpagent { 'Postfix' }
sub scan {
# @Description Detect an error from Postfix
# @Param <ref> (Ref->Hash) Message header
# @Param <ref> (Ref->String) Message body
# @Return (Ref->Hash) Bounce data list and message/rfc822 part
my $class = shift;
my $mhead = shift // return undef;
my $mbody = shift // return undef;
# ____ _ __ _
# | _ \ ___ ___| |_ / _(_)_ __
# | |_) / _ \/ __| __| |_| \ \/ /
# | __/ (_) \__ \ |_| _| |> <
# |_| \___/|___/\__|_| |_/_/\_\
#
# Pre-Process email headers and the body part of the message which generated
# by Postfix e.g.)
# From: MAILER-DAEMON (Mail Delivery System)
# Subject: Undelivered Mail Returned to Sender
return undef unless $mhead->{'subject'} =~ $RxMTA->{'subject'};
my $commandset = []; # (Ref->Array) ``in reply to * command'' list
my $dscontents = []; # (Ref->Array) SMTP session errors: message/delivery-status
my $rfc822head = undef; # (Ref->Array) Required header list in message/rfc822 part
my $rfc822part = ''; # (String) message/rfc822-headers part
my $rfc822next = { 'from' => 0, 'to' => 0, 'subject' => 0 };
my $previousfn = ''; # (String) Previous field name
my $stripedtxt = [ split( "\n", $$mbody ) ];
my $recipients = 0; # (Integer) The number of 'Final-Recipient' header
my $connvalues = 0; # (Integer) Flag, 1 if all the value of $connheader have been set
my $connheader = {
'date' => '', # The value of Arrival-Date header
'lhost' => '', # The value of Received-From-MTA header
};
my $anotherset = {}; # Another error information
my $v = undef;
my $p = '';
push @$dscontents, __PACKAGE__->DELIVERYSTATUS;
$rfc822head = __PACKAGE__->RFC822HEADERS;
for my $e ( @$stripedtxt ) {
# Read each line between $RxMTA->{'begin'} and $RxMTA->{'rfc822'}.
if( ( grep { $e =~ $_ } @{ $RxMTA->{'rfc822'} } ) .. ( $e =~ $RxMTA->{'endof'} ) ) {
# After "message/rfc822"
if( $e =~ m/\A([-0-9A-Za-z]+?)[:][ ]*(.+)\z/ ) {
# Get required headers only
my $lhs = $1;
my $rhs = $2;
$previousfn = '';
next unless grep { lc( $lhs ) eq lc( $_ ) } @$rfc822head;
$previousfn = $lhs;
$rfc822part .= $e."\n";
} elsif( $e =~ m/\A[\s\t]+/ ) {
# Continued line from the previous line
next if $rfc822next->{ lc $previousfn };
$rfc822part .= $e."\n" if $previousfn =~ m/\A(?:From|To|Subject)\z/;
} else {
# Check the end of headers in rfc822 part
next unless $previousfn =~ m/\A(?:From|To|Subject)\z/;
next unless $e =~ m/\A\z/;
$rfc822next->{ lc $previousfn } = 1;
}
} else {
# Before "message/rfc822"
next unless ( grep { $e =~ $_ } @{ $RxMTA->{'begin'} } ) .. ( grep { $e =~ $_ } @{ $RxMTA->{'rfc822'} } );
next unless length $e;
if( $connvalues == scalar( keys %$connheader ) ) {
# Final-Recipient: RFC822; userunknown@example.jp
# X-Actual-Recipient: RFC822; kijitora@example.co.jp
# Action: failed
# Status: 5.1.1
# Remote-MTA: DNS; mx.example.jp
# Diagnostic-Code: SMTP; 550 5.1.1 <userunknown@example.jp>... User Unknown
# Last-Attempt-Date: Fri, 14 Feb 2014 12:30:08 -0500
$v = $dscontents->[ -1 ];
if( $e =~ m/\AFinal-Recipient:[ ]*rfc822;[ ]*(.+)\z/ ) {
# Final-Recipient: RFC822; userunknown@example.jp
if( length $v->{'recipient'} ) {
# There are multiple recipient addresses in the message body.
push @$dscontents, __PACKAGE__->DELIVERYSTATUS;
$v = $dscontents->[ -1 ];
}
$v->{'recipient'} = $1;
$recipients++;
} elsif( $e =~ m/\AX-Actual-Recipient:[ ]*rfc822;[ ]*([^ ]+)\z/ ||
$e =~ m/\AOriginal-Recipient:[ ]*rfc822;[ ]*([^ ]+)\z/ ) {
# X-Actual-Recipient: RFC822; kijitora@example.co.jp
# Original-Recipient: rfc822;kijitora@example.co.jp
$v->{'alias'} = $1;
} elsif( $e =~ m/\AAction:[ ]*(.+)\z/ ) {
# Action: failed
$v->{'action'} = lc $1;
} elsif( $e =~ m/\AStatus:[ ]*(\d[.]\d+[.]\d+)/ ) {
# Status: 5.1.1
# Status:5.2.0
# Status: 5.1.0 (permanent failure)
$v->{'status'} = $1;
} elsif( $e =~ m/Remote-MTA:[ ]*dns;[ ]*(.+)\z/ ) {
# Remote-MTA: DNS; mx.example.jp
$v->{'rhost'} = lc $1;
} elsif( $e =~ m/\ALast-Attempt-Date:[ ]*(.+)\z/ ) {
# Last-Attempt-Date: Fri, 14 Feb 2014 12:30:08 -0500
#
# src/bounce/bounce_notify_util.c:
# 681 #if 0
# 682 if (dsn->time > 0)
# 683 post_mail_fprintf(bounce, "Last-Attempt-Date: %s",
# 684 mail_date(dsn->time));
# 685 #endif
$v->{'date'} = $1;
} else {
if( $e =~ m/\ADiagnostic-Code:[ ]*(.+?);[ ]*(.+)\z/ ) {
# Diagnostic-Code: SMTP; 550 5.1.1 <userunknown@example.jp>... User Unknown
$v->{'spec'} = uc $1;
$v->{'diagnosis'} = $2;
$v->{'spec'} = 'SMTP' if $v->{'spec'} eq 'X-POSTFIX';
} elsif( $p =~ m/\ADiagnostic-Code:[ ]*/ && $e =~ m/\A[\s\t]+(.+)\z/ ) {
# Continued line of the value of Diagnostic-Code header
$v->{'diagnosis'} .= ' '.$1;
$e = 'Diagnostic-Code: '.$e;
}
}
} else {
# If you do so, please include this problem report. You can
# delete your own text from the attached returned message.
#
# The mail system
#
# <userunknown@example.co.jp>: host mx.example.co.jp[192.0.2.153] said: 550
# 5.1.1 <userunknown@example.co.jp>... User Unknown (in reply to RCPT TO
# command)
if( $e =~ m/\s[(]in reply to .*([A-Z]{4}).*/ ) {
# 5.1.1 <userunknown@example.co.jp>... User Unknown (in reply to RCPT TO
push @$commandset, $1;
} elsif( $e =~ m/([A-Z]{4})\s*.*command[)]\z/ ) {
# to MAIL command)
push @$commandset, $1;
} else {
if( $e =~ m/\AReporting-MTA:[ ]*dns;[ ]*(.+)\z/ ) {
# Reporting-MTA: dns; mx.example.jp
next if $connheader->{'lhost'};
$connheader->{'lhost'} = $1;
$connvalues++;
} elsif( $e =~ m/\AArrival-Date:[ ]*(.+)\z/ ) {
# Arrival-Date: Wed, 29 Apr 2009 16:03:18 +0900
next if $connheader->{'date'};
$connheader->{'date'} = $1;
$connvalues++;
} elsif( $e =~ m/\A(X-Postfix-Sender):[ ]*rfc822;[ ]*(.+)\z/ ) {
# X-Postfix-Sender: rfc822; shironeko@example.org
$rfc822part .= sprintf( "%s: %s\n", $1, $2 );
} else {
# Alternative error message and recipient
if( $e =~ m/\A[<]([^ ]+[@][^ ]+)[>] [(]expanded from [<](.+)[>][)]:\s*(.+)\z/ ) {
# <r@example.ne.jp> (expanded from <kijitora@example.org>): user ...
$anotherset->{'recipient'} = $1;
$anotherset->{'alias'} = $2;
$anotherset->{'diagnosis'} = $3;
} elsif( $e =~ m/\A[<]([^ ]+[@][^ ]+)[>]:(.*)\z/ ) {
# <kijitora@exmaple.jp>: ...
$anotherset->{'recipient'} = $1;
$anotherset->{'diagnosis'} = $2;
} else {
# Get error message continued from the previous line
next unless $anotherset->{'diagnosis'};
if( $e =~ m/\A\s{4}(.+)\z/ ) {
# host mx.example.jp said:...
$anotherset->{'diagnosis'} .= ' '.$e;
}
}
}
}
}
} # End of if: rfc822
} continue {
# Save the current line for the next loop
$p = $e;
$e = '';
}
unless( $recipients ) {
# Fallback: set recipient address from error message
if( defined $anotherset->{'recipient'} && length $anotherset->{'recipient'} ) {
# Set recipient address
$dscontents->[-1]->{'recipient'} = $anotherset->{'recipient'};
$recipients++;
}
}
return undef unless $recipients;
require Sisimai::String;
require Sisimai::RFC3463;
require Sisimai::RFC5322;
for my $e ( @$dscontents ) {
# Set default values if each value is empty.
map { $e->{ $_ } ||= $connheader->{ $_ } || '' } keys %$connheader;
$e->{'agent'} ||= __PACKAGE__->smtpagent;
$e->{'command'} = shift @$commandset || '';
if( exists $anotherset->{'diagnosis'} && length $anotherset->{'diagnosis'} ) {
# Copy alternative error message
$e->{'diagnosis'} ||= $anotherset->{'diagnosis'};
if( $e->{'diagnosis'} =~ m/\A\d+\z/ ) {
# Override the value of diagnostic code message
$e->{'diagnosis'} = $anotherset->{'diagnosis'};
}
}
$e->{'diagnosis'} = Sisimai::String->sweep( $e->{'diagnosis'} );
$e->{'spec'} ||= 'SMTP' if $e->{'diagnosis'} =~ m/host .+ said:/;
if( scalar @{ $mhead->{'received'} } ) {
# Get localhost and remote host name from Received header.
my $r = $mhead->{'received'};
$e->{'lhost'} ||= shift @{ Sisimai::RFC5322->received( $r->[0] ) };
$e->{'rhost'} ||= pop @{ Sisimai::RFC5322->received( $r->[-1] ) };
}
if( length( $e->{'status'} ) == 0 || $e->{'status'} =~ m/\A\d[.]0[.]0\z/ ) {
# There is no value of Status header or the value is 5.0.0, 4.0.0
my $r = Sisimai::RFC3463->getdsn( $e->{'diagnosis'} );
$e->{'status'} = $r if length $r;
}
$e->{'softbounce'} = Sisimai::RFC3463->is_softbounce( $e->{'status'} );
}
return { 'ds' => $dscontents, 'rfc822' => $rfc822part };
}
1;
__END__
=encoding utf-8
=head1 NAME
Sisimai::MTA::Postfix - bounce mail parser class for C<Postfix>.
=head1 SYNOPSIS
use Sisimai::MTA::Postfix;
=head1 DESCRIPTION
Sisimai::MTA::Postfix parses a bounce email which created by C<Postfix>. Methods
in the module are called from only Sisimai::Message.
=head1 CLASS METHODS
=head2 C<B<version()>>
C<version()> returns the version number of this module.
print Sisimai::MTA::Postfix->version;
=head2 C<B<description()>>
C<description()> returns description string of this module.
print Sisimai::MTA::Postfix->description;
=head2 C<B<smtpagent()>>
C<smtpagent()> returns MTA name.
print Sisimai::MTA::Postfix->smtpagent;
=head2 C<B<scan( I<header data>, I<reference to body string>)>>
C<scan()> method parses a bounced email and return results as a array reference.
See Sisimai::Message for more details.
=head1 AUTHOR
azumakuniyuki
=head1 COPYRIGHT
Copyright (C) 2014 azumakuniyuki E<lt>perl.org@azumakuniyuki.orgE<gt>,
All Rights Reserved.
=head1 LICENSE
This software is distributed under The BSD 2-Clause License.
=cut
| gitpan/Sisimai | lib/Sisimai/MTA/Postfix.pm | Perl | bsd-2-clause | 13,683 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.