App-Cheats
view release on metacpan or search on metacpan
connect(sender_object, &sender_object::signal, receiver_object , &receiver_object::slot);
#############################################################
## C,CPP - Socket Programming
#############################################################
# Protocol families, same as address families (socket)
vii /usr/src/linux/include/linux/socket.h:204
#define PF_INET AF_INET
# Client address given a request (c,cpp)
const HTTPServerRequest &request
auto clientAddress = request.clientAddress().host().toString();
#############################################################
## C,CPP - Static Archive Library (.a)
#############################################################
# View contents of an archive library
# "Tell me"
ar -t libOmsFilter.a
ar -tv libOmsFilter.a
# Add new files to archive
ar -rv libMy.a 1.o 2.o
# Show verbose messages (info)
ar -rv libMy.a 1.o
# Append to archive (no duplicates)
# "Read-in"
ar -rv libMy.a 1.o
ar -rv libMy.a 2.o
ar -rv libMy.a 3.o
# Append to archive (allow duplicates)
ar -qv libMy.a 1.o
ar -qv libMy.a 1.o
ar -qv libMy.a 1.o
# Delete a member from an archive
ar -dv libMy.a 1.o
# Checkout a member from an archive
# "Extract" (but still stays in archive)
ar -xv libMy.a 1.o
# Insert after 1.o (order,archive)
ar -rav 1.o libMy.a 3.o 4.o 5.o
#
# Order is not quite expected since the insert location
# is constant ("|" below).
# 1.o | 5.o 4.o 3.o 2.o
# Update a member of an archive of if a newer file exists
ar -ruv libMy.a 1.o
# Alternate syntax to link to an archive library
-lABC # looks for libABC.so, then for libABC.a
-l:libABC.a # Looks for libABC.a (more explicit, but simplier)
#############################################################
## C,CPP - String
#############################################################
# Convert anything to a string in cpp using string streams (DWORD,int)
#include <string>
#include <sstream>
if(it->GetName() == L"MyProg.exe"){
std::stringstream ss;
ss << "taskkill /T /F /PID " << it->GetPID();
std::string command = ss.str();
system(command.c_str());
}
# String comparison breakpoint in Visual studio
strcmp(static_cast<const char *>(name),"place_absolute")==0
// In cpp split a string by a delimeter and put the contents into a map (or vector)
std::map<std::string, int> map_column_names;
std::istringstream ss(default_columns);
std::string token;
while (std::getline(ss, token, ',')) {
map_column_names[token] = 1;
}
# Convert a float to an integer in cpp.
int myInt = static_cast<int>(myFloat);
# Check if a string is NOT found in a vector in cpp
# This returns a bool (true if present, false otherwise)
#
if ( std::find(vec.begin(), vec.end(), item) == vec.end() )
do_this();
else
do_that();
# Cpp double to string conversion
std::string makeTime = std::to_string(time_span.count());
# Cpp uses floor() to get the integer part of a float.
# like int() in perl.
# ceil() returns the smallest integer, but rounding up.
#
# ceil did not for so used this instead:
int total_pages = (amount + tool_limit - 1) / tool_limit;
# Cpp std::string for const char *
string myStr;
myStr.c_str();
# Raw string in CPP. Do not need to escape characters.
# R"ABC(TEXT)ABC";
#
R"sql(CREATE TABLE IF NOT EXISTS version (
version INTEGER
);)sql"
#############################################################
## PDF
#############################################################
# View pdf files on linux
xpdf perl6intro.pdf
# Parse PDF files (convert to text)
pdftotext file.pdf
pdftotext file.pdf -
# Make pdf of differences on Linux
kdiff3 file1 file2
File->Print
Properties->PageSize = A1 -> Save
Print to pdf
# Simple perl library for generating pdf files
sudo apt-get install libpdf-api2-simple-perl
# Simple perl library for generating pdf files with tables
# Need also PDF::API2
sudo apt-get install libpdf-table-perl
# Get the dimensions of a PNG image file (picture)
sudo apt-get install libimage-size-perl
perl -MImage::Size -le 'print for imgsize("logo.png");'
# HTML to PDF tool
sudo apt-get install wkhtmltopdf
# Send output to pdf
# setup
sudo apt-get install aha
echo -e "Im $RED RED $RESTORE now" | aha
#############################################################
## Perl General
#############################################################
# Zen of Perl
# wget http://www.perlmonks.org/?abspart=1;node_id=752029;displaytype=displaycode;part=1
Beauty is subjective.
Explicit is recommended, but not required.
Simple is good, but complex can be good too.
And although complicated is bad,
Verbose and complicated is worse.
Brief is better than long-winded.
But readability counts.
So use whitespace to enhance readability.
Not because you're required to.
Practicality always beats purity.
In the face of ambiguity, do what I mean.
There's more than one way to do it.
Although that might not be obvious unless you're a Monk.
At your discretion is better than not at all.
Although your discretion should be used judiciously.
Just because the code looks clean doesn't mean it is good.
Just because the code looks messy doesn't mean it is bad.
Reuse via CPAN is one honking great idea -- let's do more of that
# Zen of Perl
According to Larry Wall, there are three great virtues of a programmer; Laziness, Impatience and Hubris
- Laziness:
- The quality that makes you go to great effort to reduce overall energy expenditure.
- It makes you write labor-saving programs that other people will find useful and
- document what you wrote so you don't have to answer so many questions about it.
- Impatience:
- The anger you feel when the computer is being lazy.
- This makes you write programs that don't just react to your needs,
- but actually anticipate them.
- Or at least pretend to.
- Hubris:
- The quality that makes you write (and maintain) programs that other
- people won't want to say bad things about.
# Create a modulino (Module/program that can be also run standalone/by itself)
run unless caller;
# Use yadda yadda to denote not yet implemented code.
perl -E 'sub F{} F'
perl -E 'sub F{...} F'
Unimplemented at -e line 1.
#############################################################
## Perl Arrays
#############################################################
# Function to shuffle/mix the elements of an array
perl -le 'sub shuf{ my @a=\(@_); my $n; my $i=@_; map{ $n=rand($i--); (${$a[$n]}, $a[$n]=$a[$i])[0] }@_ } print for shuf qw/a b c/'
#
# Simplified
perl -le '@a=\(qw/a b c/); $i=@a; print for map{ $n=rand($i--); (${$a[$n]}, $a[$n]=$a[$i])[0] }@a'
perl -le '$i=@a=\(qw/a b c/); print for map{ $n=rand($i--); (${$a[$n]}, $a[$n]=$a[$i])[0] }@a'
#
# Even simplier
# Concept:
# 1. Have references to a list:
# @a = [r1,r2,r3] # where r1=\a, r2=\b, r3=\c
# 2. Spin the dice:
# $n = random from 0 to last element
# 3. return value will be reference value at element $n
# 4. Trick is that each time through the loop:
# A. max element is decreased ($i--)
# B. previous element (which was already used) is assigned the last element size
# a. means that if "a" is selected first time, its spot will be taken by "c".
# in the next round these will be available:
# 0: c # took spot of "a"
# 1: b
# b if "b" is selected first time, "b"'s spot is taken by "c"
# 0: a
# 1: c
# c. if "c" is selected first time, things proceed as normal
# 0: a
# 1: b
perl -le '@a=\(qw/a b c/); $i=@a; map{ $n=rand($i--); print ${$a[$n]}; $a[$n]=$a[$i] }@a'
perl -le '$i=@a=\(qw/a b c/); map{ $n=rand($i--); print ${$a[$n]}; $a[$n]=$a[$i] }@a'
perl -le '$i=@a=\(qw/a b c/); $n=rand($i--), print(${$a[$n]}), $a[$n]=$a[$i] for @a'
#############################################################
## Perl Modules - Mojolicious::Plugin::Directory
#############################################################
# Similar to python's simple http server
python -m SimpleHTTPServer 8080
#
cpanm Mojolicious::Plugin::Directory
perl -Mojo -MCwd=getcwd -E 'a->plugin("Directory", root => getcwd())->start' daemon
#############################################################
## Perl Modules - Moose
#############################################################
# Override a method that is defined in a role (Moose)
$Self->meta->add_method(FinishHook => sub { say 'FINISH!!!' });
# Override a class method that is defined in a role (Moose,around)
# Approach 1 - get_method, add_method, execute.
#
+ my $Orig = $Meta->get_method($Method);
+ $Meta->add_method( $Method => sub {
+ my ($Self,%Param) = @_;
+ $Orig->execute($Self,%Param);
+ return 1;
+ });
# Override a class method that is defined in a role (Moose,around)
# Approach 2 - add_method_modifier.
#
+ add_method_modifier $Meta, 'around', [ $Method, sub {
+ my ($Orig,$Self,%Param) = @_;
+ $Self->$Orig(%Param);
+ return 1;
+ }];
# Override a class method that is defined in a role (Moose,around)
# Approach 3 - Moose::around meta.
#
+ # 'around' will not work since it uses currying and
+ # prepends the current class name.
+ # 'Moose::around' avoids currying.
+ Moose::around $Meta, $Method => sub {
+ my ($Orig,$Self,%Param) = @_;
+ $Orig->($Self,%Param);
+ return 1;
+ };
# Override a class method that is defined in a role (Moose,around)
# Approach 4 - Moose::around class.
#
+ Moose::around $Package, $Method => sub {
+ my ($Orig,$Self,%Param) = @_;
+ $Orig->($Self,%Param);
+ return 1;
+ };
# The basic Moose type hierarchy looks like this (perl,OOP):
Any
Item
Bool
Maybe[`a]
Undef
Defined
Value
Str
Num
Int
ClassName
RoleName
Ref
ScalarRef[`a]
ArrayRef[`a]
HashRef[`a]
CodeRef
RegexpRef
GlobRef
FileHandle
Object
#############################################################
## Perl Modules - mro
#############################################################
# As of v5.10, the traversal is configurable.
# In fancy terms, this is the method resolution order, which you select with the mro pragma (see Chapter 29):
# The C3 algorithm traverses @INC so it
# finds inherited methods that are closer
# in the inheritance graph. Said another way, that means that no superclass will be searched before one of its subclasses.
package Mule;
use mro 'c3';
use parent qw(Donkey Horse);
#############################################################
## Perl Modules - Net::SSLeay
#############################################################
# Installation is failing:
cpanm Net::SSLeay
# /usr/bin/ld: cannot find -lz: No such file or directory
# Install:
sudo apt install zlib1g-dev
#############################################################
## Perl Modules - O::Xref
#############################################################
# Debug a perl script. Find all usage of subroutines and variables
perl -MO=Xref fetch_excel.p | less
#############################################################
## Perl Modules - Object::Pad
#############################################################
#############################################################
## Perl Modules - Reply
#############################################################
# Using a read,evaluate,print,loop in perl.
# Not working with arrow keys.
perl -MReply -E 'Reply->new->run'
#############################################################
## Perl Modules - Safe
#############################################################
# Run code in a safer environment
perl -MSafe -le '$comp=Safe->new; $code=q(use v5.10; print "hello Safe!"); $comp->reval($code) or die $@'
'require' trapped by operation mask at (eval 5) line 1.
# Safely run substitution.
# Prevents running other commands (like unlink).
perl -MSafe -E '$_ = "abc"; my $comp = Safe->new; $comp->reval(q(s/./print 123/e)); say $@ if $@; say'
'print' trapped by operation mask at (eval 7) line 1.
abc
perl -MSafe -E '$_ = "abc"; my $comp = Safe->new; $comp->reval(q(s/./print 123/)); say $@ if $@; say'
print 123bc
# Safely run substitution.
# Share/permit a global variable.
perl -MSafe -E 'our $var = "abc"; my $comp = Safe->new; $comp->share(q($var)); $comp->reval(q($var =~ s/./print 123/)); say $@ if $@; say $var'
print 123bc
perl -MSafe -E 'our $var = "abc"; my $comp = Safe->new; $comp->share(q($var)); $comp->reval(q($var =~ s/./print 123/e)); say $@ if $@; say $var'
'print' trapped by operation mask at (eval 7) line 1.
abc
perl -MSafe -E '$_ = "abc"; my $comp = Safe->new; $comp->reval(q(s/.[/print 123/)); say $@=~s/ at .+ line .+//r if $@; say'
Unmatched [ in regex; marked by <-- HERE in m/.[ <-- HERE /
abc
# Permit actions to be done
perl -MSafe -le '$comp=Safe->new; $comp->permit("require"); $code=q(use v5.10; print "hello Safe!"); $comp->reval($code) or die $@'
'print' trapped by operation mask at (eval 5) line 2.
perl -MSafe -le '$comp=Safe->new; $comp->permit(qw(require print)); $code=q(use v5.10; print "hello Safe!"); $comp->reval($code) or die $@'
hello Safe!
# Find/View/see all Opcodes for Safe
perl -MOpcode=opdump -e opdump
# Find/View/see all Opcodes for Safe that include a string
perl -MOpcode=opdump -e 'opdump shift' item
# Find Opcode for safe that fints a specific attribute
perl -MOpcode=opdump -e 'opdump shift' ATTRIBUTE
# Run code to evaluate arithemetic
perl -MSafe -le '$comp=Safe->new; $comp->deny(qw(:default)); $comp->permit(qw(padany lineseq const add leaveeval subtract)); while(<>){chomp; $res=$comp->reval($_) or warn $@ and next; print "$_ = $res"}'
#############################################################
## Perl Modules - Scalar::Util
#############################################################
# perl looks_like_number example.
perl -MScalar::Util=looks_like_number -E 'printf("%s: %s\n", $_, looks_like_number($_)) for qw/ 1 cat bat 1.5 1e10 4.5 fat /'
1: 1
cat:
bat:
1.5: 1
1e10: 1
4.5: 1
fat:
# Example of using a dualvar in perl.
use Scalar::Util 'dualvar';
my $name = dualvar 0, 'Fire and Lightning';
say 'Boolenan true' if !! $name;
say 'Numeric true' unless 0 + $name;
say 'String true' if '' . $name;
#############################################################
## Perl Modules - Set::Scalar
#############################################################
# Install library to work with sets
sudo apt-get install libset-scalar-perl
# Working with sets in perl (examples)
perl -MSet::Scalar -le '$s1=Set::Scalar->new(qw/1 2 3/); $s2=Set::Scalar->new(qw/2 4 6/); print for $s1-$s2'
perl -MSet::Scalar -le '$s=Set::Scalar; $s1=$s->new(qw/1 2 3/); $s2=$s->new(qw/2 4 6/); print for $s1-$s2'
# Example of making a set: on init or interatively.
# Set is basically a hash (no doubled keys).
perl -MSet::Scalar -E '
my $s = Set::Scalar->new;
$s->insert($_) for 2,4,6,4;
say $s;
'
(2 4 6)
perl -MSet::Scalar -E '
my $s = Set::Scalar->new(2,4,6,4);
say $s;
'
(2 4 6)
# Get all set elements.
perl -MSet::Scalar -E '
my $s = Set::Scalar->new( 2,4,6,4 );
say for sort $s->elements;
'
2
4
6
#############################################################
## Perl Modules - Socket
#############################################################
# Simple client using perl Socket module.
use Socket;
my $socket;
my $port = 171717;
my $address = 'localhost';
( run in 1.783 second using v1.01-cache-2.11-cpan-9581c071862 )