How do I set up my POE::Filter to receive the entire chunk of data returned from the server? - perl

I tried the following
my $filter = POE::Filter::Line->new(OutputLiteral => '');
my $wheel = POE::Wheel::ReadWrite->new(
Handle => $socket,
Filter => $filter,
InputEvent => 'on_input',
ErrorEvent => 'on_error',
FlushedEvent => 'on_flush',
);
But on_input is called several times with each line separately in ARG0. How do I get it all together? Doesn't setting setting OutputLiteral to '' change the filter's understanding of what a "line" is?

First of all, you are reading from the filter, so it's InputLiteral which is important here, not OutputLiteral. Second, you can't have an empty InputLiteral (if you try, it will just autodetect the input literal). Consequently, you can't use POE::Filter::Line to get all the data, because it is made for parsing line-terminated records. Use POE::Filter::Stream instead.

Related

Get Values out of Complex Perl Hash Structures

With the following Code I can fetch Data stored in a Hash from a Database and print it out:
use Data::Dumper;
my $fdx = $s->field(); # get Hashreference from Database
print Dumper($fdx); # print out Hash
The (important part of the) Output looks like this:
$VAR1 = bless( {
'selectable' => 'true',
'_PARENT_OBJECT' => bless( {
'dirtyFlag' => 1,
'path' => undef,
'testItems' => [],
'data' => {
'TEST_10' => {
'atm_rundatahistory' => {
'1523964918' => {
'atm_prid' => {
'content' => '',
'label' => 'Problem Report IDs',
'raw' => ''
}, ...
'1523964410' => {
'atm_prid' => {
'label' => 'Problem Report IDs',
'raw' => '23361234',
'content' => '23361234'
}, ...
'Test_10' is one of hundreds of Tests, '1523964918' is one of many unix timestamps, so basically its a 32 Bit Integer, but I dont know which numbers the timestamps contain.
How do I print out / access the values for 'content' (in this case '23361234') of the most inner Hashes, for all Tests and unix timestamps, if they exist?
from here on I will describe my thoughts and what I have tried, its not necessary to read any further for this question.
I think the code I am looking for is something like:
foreach my $val($fdx{_PARENT_OBJECT}{data}{"TEST_*"}{atm_rundatahistory}{"********"}{atm_prid}{content})
print("\n$val");
However I don't know the exact Syntax, and neither do I know which placeholders to set for "Test_10", since there are many tests numbers, e.g. "...Test_132...Test_134" and the Unix timestamps can be any 32 Bit Integer, so I guess I can use start as a placeholder? e.g. "********".
After some hours of searching on the web, I haven't found a understandable tutorial on how to access values from complex Perl hash structures, I guess there are some simple syntax-rules to know and you can get any value of even very complex data structures without to much effort.
I've already read perldoc_perlreftut. If there is any other easy to understandable tutorial for these kind of problems, please recommend them to me. I don't really know how I can learn to handle such complex data structures in Perl myself.

WolframAlpha API: how to specify multiple pods?

Currently I am specifying multiple pods in the following way:
my $q = $wa->query(
'input' => $input,
'format' => 'plaintext',
'includepodid' => ['Input', 'Result', 'WeatherForecast:WeatherData', 'ForecastCharts:WeatherData'],
'reinterpret' => 'true',
);
However it then returns empty result – number of pods is undefined, so as are other fields. Setting only a single pod id with:
'includepodid' => 'Result'
does work so the code is overall correct. Using [ 'Result' ] yields the same incorrect behavior.
It's maybe a little late for you but for anyone else experiencing this: You mustn't set the includepodid parameter with delimiters you have to set it multiple times meaning instead of this:
...&includepodid=ID1,ID2
do this:
...&includepodid=ID1&includepodid=ID2
Worked for me though..

phpseclib createKey() using own primes

Is it possible to generate private and public key in PKCS#1 format using phpseclib and my own primes? I mean I already have p and q and I want to generate both keys. I am trying to do something like this:
$p = new Math_BigInteger(...);
$q = new Math_BigInteger(...);
$custom_primes = serialize(array('primes'=>array(1=>$p,2=>$q)));
extract($rsa->createKey(512,10,$custom_primes));
But this gives me the fatal error:
Fatal error: Call to a member function divide() on a non-object in /volume1/web/phpseclib/Crypt/RSA.php on line 705
I checked this and it is trying to divide:
list($temp) = $lcm['top']->divide($lcm['bottom']);
Obviously I am not setting up lcm in my $custom_primes structure as I only have my two primes. So the question is: is it possible at all in phpseclib?
It looks like you're trying to use phpseclib's partial key functionality to achieve this. Problem is that expects more than just primes. See this, for example:
return array(
'privatekey' => '',
'publickey' => '',
'partialkey' => serialize(array(
'primes' => $primes,
'coefficients' => $coefficients,
'lcm' => $lcm,
'exponents' => $exponents
))
);
$lcm is defined, initially, like this:
$lcm = array(
'top' => $this->one->copy(),
'bottom' => false
);
So maybe try doing that as well. You can probably strip out all of the calculation functions
from phpseclib, do them yourself and then pass $partial into phpseclib and let it generate a key in whatever format you want it generated in.

are there iterators and loops in puppet?

When I define(?) a resource e.g. to ensure dir structure, are there any loops available?
Like that:
for X in [app1,app2] do:
file { '/opt/app/' + X:
ensure => directory,
owner => 'root',
group => 'root',
mode => '0644',
}
I have tens of directories and I am really tired with declaring it in puppet.. It would take 15 LOC of bash.
Any ideas?
Older versions of the puppet language have no support for loops.
But you can use an array instead of a simple string for the title and declare several resources at the same time with the same params:
$b = '/opt/app'
file { [ "$b/app1", "$b/app2" ]:
ensure => directory,
owner => 'root',
group => 'root',
mode => 0644,
}
You can also declare many resources of the same type with different params by ending each resource with a ;, which is a bit more compact than repeating the file and the {s and }s:
file {
[ "$b/app1", "$b/app2" ]:
ensure => directory,
owner => 'root',
group => 'root',
mode => 0755;
[ "$b/app1/secret", "$b/app2/secret" ]:
ensure => directory,
owner => 'root',
group => 'root',
mode => 0700;
}
In the specific case of files, you can set up a source and use recursion:
file { "/opt/app":
source => "puppet:///appsmodule/appsdir",
recurse => true;
}
(that would require having a source of that directory structure for puppet to use as the source)
You can define a new resource type to reuse a portion of the param multiple times:
define foo {
file {
"/tmp/app/${title}":
ensure => directory,
owner => 'root',
mode => 0755;
"/tmp/otherapp/${title}":
ensure => link,
target => "/tmp/app/${title}",
require => File["/tmp/app/${title}"]
}
}
foo { ["app1", "app2", "app3", "app4"]: }
Starting with Puppet 2.6, there's a Ruby DSL available that has all the looping functionality you could ask for: http://www.puppetlabs.com/blog/ruby-dsl/ (I've never used it, however). In Puppet 3.2, they introduced some experimental loops, however those features may change or go away in later releases.
As of version 3.2 there are lambdas
You must set parser = future in puppet.conf.
$a = [1,2,3]
each($a) |$value| { notice $value }
Another option for declaring multiple defined types is create_resources. Pass it a hash of hashes:
create_resources(file, {
'/tmp/test1' => {
ensure => directory,
owner => 'root',
group => 'root',
mode => '0644',
},
'/tmp/test2' => {
ensure => directory,
owner => 'www-data',
group => 'www-data',
mode => '0755',
},
})
As of Puppet 4 (and the "future parser" of late versions of Puppet 3) the Puppet DSL has iteration functions similar in form and function to some of the methods of Ruby arrays and hashes:
each - evaluates a block of code (formally, a lambda) for each element of an array or hash
filter - applies a lambda to each element of an array or hash and returns an array or hash of those for which the lambda evaluated to true
map - applies a lambda to each element of an array or hash, and returns an array of the results
reduce - applies a lambda to each element of an array or hash to build up a single result, which it returns
There is no indexed for loop along the lines of C's or Java's, but you can combine array sectioning with any of the functions above to achieve iteration over a subset of a data structure. There is no indefinite iteration along the lines of a C or Java while loop.
Of course, you can still use the resource-centric approaches described in other answers, and sometimes one of those is indeed the best available approach. You cannot any longer use Ruby DSL, however; it is removed altogether from Puppet 4. Among the iteration functions, the ability to define custom functions, the ascension of data-centric approaches into favor, and all Puppet's historic standard features, Ruby DSL seems not much missed.
Yes. "Ruby DSL" could help, just use file extension ".rb" instead of ".pp" in manifest and you can define puppet "type" like this:
define 'myapps::structure', :applist do
#applist.each do |app|
file( #name+'/'+app,
:ensure => directory,
:owner => 'root',
:group => 'root',
:mode => '0644')
end
end
Classes and nodes also can be defined in similar way. Notice however that this feature is deprecated since release 3

How to get affected number of rows using mongodb ,php driver

I have two problem : How can I get affected rows by php mongodb driver ,and how about the last insert id ? thanks .
You can get number of results right from the cursor using count function:
$collection->find()->count();
You can even get number of all records in collection using:
$collection->count();
Using insert method, _id is added to input array automatically.
$a = array('x' => 1);
$collection->insert($a,array('safe'=>true));
var_dump($a);
array(2) {
["x"]=>
int(1)
["_id"]=>
object(MongoId)#4 (0) {
}
}
I don't believe that there is any type of affected_rows() method at your disposal with mongodb. As for the last insert _id You can generate them in your application code and include them in your insert, so there's really no need for any mysql like insert_id() method.
$id = new MongoId();
$collection->insert(array('
'_id' => $id,
'username' => 'username',
'email' => 'johndoe#gmail.com'
'));
Now you can use the object stored in $id however you wish.
Maybe MongoDB::lastError is what you are looking for:
(http://php.net/manual/en/mongodb.lasterror.php)
It calls the getLastError command:
(http://www.mongodb.org/display/DOCS/getLastError+Command)
which returns, among other things:
n - if an update was done, this is the number of documents updated.
For number of affected rows:
$status = $collection->update( $criteria, array( '$set' => $data ) );
$status['n']; // 'n' is the number of affected rows
If you have the output of your action, you can call relative function:
// $m hold mongo library object
$output = $m->myCollection->updateOne([
'_id' => myMongoCreateID('56ce2e90c9c037dba19c3ce1')], [
'$set' => ['column' => 'value']
]);
// get number of modified records
$count = $output->getModifiedCount();
$output is of of type MongoDB\UpdateResult. Relatively check following files to figure out the best function to find inserted, deleted, matched or whatever result you need:
https://github.com/mongodb/mongo-php-library/blob/master/src/InsertManyResult.php
https://github.com/mongodb/mongo-php-library/blob/master/src/DeleteResult.php
https://github.com/mongodb/mongo-php-library/blob/master/src/InsertOneResult.php
https://github.com/mongodb/mongo-php-library/blob/master/src/UpdateResult.php