App-Cheats

 view release on metacpan or  search on metacpan

cheats.txt  view on Meta::CPAN

# Read lines from a file (c program)
char *file_name = strcat(name, ".cmd");
char line[512];
FILE *fp;
fp = fopen(file_name, "r");
if(fp == NULL)
{
   sendlog("ERROR: Could not open file: '%s'", file_name);
   return 1;
}
while (fgets( line, sizeof(line), fp ) != NULL)
{
   line[strlen(line) - 1] = '\0';
   sendlog("Line1: '%s'", line);
   yyParseAndExecute( line );
}

# The -m32 flag is necessary for both compiling and linking (gcc,DES)

# Sample C program. Prints to STDOUT and STDERR
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
	fprintf(stderr, "Select folder:\n");
	fprintf(stderr, "1 C:\\TOOLS\n");
	fprintf(stderr, "2 C:\\BAT\n");
	printf("C:\\TOOLS\n");
	fprintf(stderr, "3 C:\\BAT2\n");
	return 0;
}

# Fix Error: forbids converting a string constant to 'char*'
argv[1] = (char *) "name = bob";


#############################################################
## C,CPP - Options/Environmental Variables
#############################################################

# C,CPP - Options/Environmental Variables
C_INCLUDE_PATH  - Additional directories to
                  search for C header files.
LIBRARY_PATH    - Additional directories to
                  search for libraries during
                  linking.
LD_LIBRARY_PATH - Additional directories to
                  search for shared libraries
                  at runtime.
-I              - Specify additional directories
                  to be searched for header
                  files during compilation.
-L              - Specify additional directories
                  to be searched for libraries
                  during linking.


#############################################################
## C,CPP Asynchronous (Threads)
#############################################################

# Run a process/function async (thread)
# Add this to makefile
LIB += -pthread
#
# Add library
#include <pthread.h>
#
# Declare threads
pthread_t threads[1];
#
# Create threads and get return code
# Sending pattern as parameter (only one allowed)
# Thread ID is first parameter
int rc;
rc = pthread_create(&thread, NULL, send_thread, (void *) pattern  );
pattern->tid = thread;     // Save thread ID so we can later kill it (if needed)
if(rc) return;             // Error
#
# Check return value
if(rc) sendlog("ERROR: return code from pthread_create() is %d", rc);
#
# Function is declared like this:
void *send_thread (void * args){
   COMMAND_PATTERN* pattern = (COMMAND_PATTERN*) args;  // Can use pattern normally
   ...
}
#
# Make sure to end the function with this:
# (it will exit the thread. don't use in main otherwise will get defunct/zombie process)
pthread_exit(NULL);

# Determine version and library used for threads
# NPTL - Native POSIX Threads Library     # Threads share PID
# LinuxThreads                            # May be different PIDs (plus may other differences)
getconf GNU_LIBPTHREAD_VERSION            # NPTL 2.7


#############################################################
## C,CPP - Debug
#############################################################

# Sleepy poll (debug,ddd,gdb,break)
# How to debug a progam
# Then after getting in using ddd, set wait_variable=0
int wait_variable = 1; while (wait_variable) sleep(1);

# Debug a UI program (DES,UI)
# Flags after --args are passed to the program
gdb progarm --args arg1 arg2

# Debug a c program given its pid (DES,UI)
gdb --pid 21620
gdb --pid `myps | grep snv | grep -v grep | awk '{print $4}'`

# gdb debugger navitation (commands,DES,UI)
(gdb) l[ist]              # view code
(gdb) l[ist] main         # view main code
(gdb) b[reak] main        # Put a breakpoint at main()
(gdb) r[un]               # start the program
(gdb) h[elp] all          # View all help sections
(gdb) f[rame]             # Show current line (line number and file)
(gdb) c[ontinue]          # Continue to a breakpoint
(gdb) d[elete]            # Delete all breakpoints

# View all functions in ddd (gdp,debugger)
info functions

# View entry point of executable program (OMS)
readelf -h omsGUI | grep "Entry point address"
# was: 0x80524a0
ddd <pid>
att <pid>
b * 0x80524a0
c

# Problem: Debugger (ddd,gdb) is ignoring my breakpoint and
#          moving unto another function
# Answer:  Add this line inside the function you want to breakpoint
# Note:    Causes a segmentation fault SIGSEGV
*(char*)0 = 0;

# Set outer variable in bash shell (hack)
a=123; (gdb --batch-silent -ex "attach $$" -ex 'set bind_variable("a", "456", 0)'); echo $a


#############################################################
## C,CPP - Errors
#############################################################

# Error: Illegal deallocation of memory
//
// my.c:

cheats.txt  view on Meta::CPAN

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"


#############################################################
## C,CPP - Templates
#############################################################

# Function Template example in Cpp
// Make a generic to_string function to convert anything to a string
//
#include <string>
#include <sstream>
//
template <typename T>
std::string to_string (T data) {
	std::stringstream ss;
	ss << data;
	return ss.str();
}


#############################################################
## C,CPP - Threads
#############################################################

# Get the current thread's name (like thread ID, tid)
QThread::currentThread()->objectName()


#############################################################
## C,CPP - Timer
#############################################################

# Timer in Cpp
#
#include <ctime>
#include <chrono>
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
// run something
std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();
std::chrono::milliseconds rawTime = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1);
std::string stringTime = std::to_string(rawTime.count());

# Timer in Cpp (simpler)
#
#include <ctime>
#include <chrono>
//
typedef std::chrono::high_resolution_clock Time;
typedef std::chrono::milliseconds ms;
//
auto t1 = Time::now();
auto t2 = Time::now();
std::string runTime = std::to_string(std::chrono::duration_cast<ms>(t2 - t1).count());

# Timer in Cpp (as a function)
#include <ctime>
#include <chrono>
//
std::string elapsedTime(std::chrono::high_resolution_clock::time_point t1)
{
	auto t2 = std::chrono::high_resolution_clock::now();
	std::string duration = std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count());
	return duration;
}
//
auto t1 = std::chrono::high_resolution_clock::now();
// code ...
std::string generateTime = elapsedTime(t1);


#############################################################
## C,CPP - Vector
#############################################################

# Example vector in cpp
//
std::vector< std::tuple<std::string, std::string> > get_vector () {
	std::ofstream *file = nullptr;
	std::ofstream file2;
	// file->open("MAKE2.txt");
	file2.open("MAKE2.txt");
//
	std::vector< std::tuple<std::string, std::string> > myVector;
//
	myVector.push_back( std::make_tuple("test1", to_string(file)   ));

cheats.txt  view on Meta::CPAN

   word-wrap: break-word;      /* IE */
   width: 8rem;
}


#############################################################
## Cowsay
#############################################################

# Ascii art messages.
sudo apt install cowsay
cowsaw hey


#############################################################
## Dig (nslookup)
#############################################################

# Install dig command.
apt install dnsutils


#############################################################
## Docker
#############################################################

# View docker log (warnings,errors)
docker compose logs -f --tail 200

# Install a mail server using docker
sudo apt install docker docker-compose
sudo usermod -a -G docker $USER
sudo su $USER # To avoid restarting for groups to take effect
docker pull mailserver/docker-mailserver:latest

# Check docker processes
docker ps
ctop


#############################################################
## Docker Setup
#############################################################

# Enable cgroups in ubuntu (for docker)
sudo vi /etc/default/grub
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash systemd.unified_cgroup_hierarchy=1 cgroup_enable=memory cgroup_memory=1"
sudo update-grub
reboot

# Check if cgroups is enabled (ubuntu)
cat /proc/cmdline

# Check if using cgroups v1:
ls /sys/fs/cgroup
blkio  cpuacct      cpuset   freezer  memory   net_cls,net_prio  perf_event  rdma     unified
cpu    cpu,cpuacct  devices  hugetlb  net_cls  net_prio          pids        systemd

# Check if using cgroups v2:
ls /sys/fs/cgroup
cgroup.controllers  cgroup.max.descendants  cgroup.stat             cgroup.threads  system.slice
cgroup.max.depth    cgroup.procs            cgroup.subtree_control  init.scope      user.slice


#############################################################
## Docker Build
#############################################################

# Build a docker image based on the Dockerfile
cd ~/tmp/learning_docker/02-*
docker build .
docker images
# EXPOSE 80 in Dockerfile does nothing
docker run -p 3000:80 <IMAGE_ID>
http://localhost:3000/
docker ps
docker stop <CONTAINER_ID>

# Run interactive container (perl shell)
docker run -it perl
docker run -it py-max

# Restart container for CLI
docker start -a -i 99150a04a616

# Run interactive container (bash shell)
docker run -it perl bash

# Go inside a running container.
docker container exec -it feedback-app bash

# Build updated perl image.
docker build -t my-perl .
docker run my-perl -E 'say $^V'

# Rename a docker container
docker container rename <CONTAINER_ID> my-perl-container

# Restart a container
docker container start -a my-perl-container


#############################################################
## Docker Dockerfile Commands
#############################################################
# Dockerfile commands:
# These are executed only during a BUILD.
FROM perl
WORKDIR /app
COPY . /app
RUN echo "Building the image now"
RUN perl -E 'say "Image uses perl version: $^V"'

# Dockerfile commands:
# These are executed only during a RUN.
CMD [ "ls" ]
CMD [ "echo", "Run the container now" ]
CMD [ "perl", "my.pl" ]
#
ENTRYPOINT [ "perl" ]
docker run <IMAGE_ID> -E 'say $^V'

cheats.txt  view on Meta::CPAN

    - 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 -le '$i=@a=\(qw/a b c/); print(${$a[$n=rand $i--]}), $a[$n]=$a[$i] for @a'
perl -le '$i=@a=\(qw/a b c/); print ${$a[$n=rand $i--]} and $a[$n]=$a[$i] for @a'

# Get random element of an array in perl.
my @a = 4..10;
print $a [rand ~~@a]

# Print the elements of an array segregated (in parenthesis)
perl -le '@a=qw/this is an array/; local $"=")("; print "(@a)"'

# Split a list into so many parts
# Purpose: Prepare for thread usage.
perl -le '$M=10; $T=3; $from=1; while($to < $M){ $to=$from+(($M-$from+1)/$T--)-1; $to=int($to)+1 if $to != int($to); print "$from -> $to"; $from=$to+1 }'

# Take 3 elements or an array/list at a time
perl -le '@a=0..30; push @b,[splice @a,0,3] while @a; print "@$_" for @b'

# Localized an array slice for a scope
perl -le 'sub pr{print "[@a]"} @a=qw/aa bb cc/; pr; {local @a[0,2]=qw/dd ff/; pr} pr'

# Perl sample array function.
+ sub get_max_length {
+    my $last_row    = $#_;
+    my $last_column = $_[0]->$#*;
+
+    my @max = map {
+       my $col = $_;
+       max map {
+          length $_[$_][$col];
+       } 0 .. $last_row;
+    } 0 .. $last_column;
+
+    \@max;
+ }

# Iterate through index and value of an array.
perl -E '@arr = qw( a b c ); say "[$i] $v" while ($i,$v) = each @arr'
[0] a
[1] b
[2] c

# Rand from 10-15
perl -Me -E 'my @n = sort map { int rand( 6 ) + 10 } 1..100; say for c(@n)->uniq->each'

# Loop through a list of items while processing 3 at a time.
perl -E 'for my ($x,$y,$z) ( 1..50 ) { say "$x-$y-$z" }'
for my (...) is experimental at -e line 1.
1-2-3
4-5-6
7-8-9
10-11-12
13-14-15
16-17-18
19-20-21
22-23-24
25-26-27
28-29-30
31-32-33
34-35-36
37-38-39
40-41-42
43-44-45
46-47-48
49-50-


#############################################################
## Perl Array - Circular
#############################################################

# Perl Array - Circular (idiom)
sub grab_and_rotate ( \@ ) {

cheats.txt  view on Meta::CPAN



#############################################################
## Perl Modules - cpan-outdated
#############################################################

# Update outdated perl modules
cpanm App::cpanoutdated
cpan-outdated | cpanm


#############################################################
## Perl Modules - perltidy
#############################################################

# Clean up perl script
perltidy my_file

# Perltidy configuration file
vi .perltidyrc
-mbl=2 -pt=0 -b -bext='/' -blbs=1 -bom -bbb -nbl

# Tell perltidy to ignore a line
<STDIN>;    ## no critic

# html
sudo apt-get install tidy
sudo apt-get install libhtml-tidy-perl    # Perl library

# View current options when doing perltidy
perltidy my_file -dop    # --dump-options


#############################################################
## Perl Modules - re
#############################################################

# Debug a regular expression
perl -Mre=debug -le 'print "abc:def-hij"=~/\w+/'
perl -Mre=debug -e 'print if "aaa:bbb" =~ /\w+/'
perl -Mre=Debug,PARSE -e 'print if "aaa:bbb" =~ /\w+/'

# Debug a regular expression (with some color)
perl -Mre=debugcolor -le 'print "abc:def-hij"=~/\w+/'

# Check if certain words are in order in a file
echo "line1 line2" | perl -0777nlE 'INIT{-t and die; $a=join".*?",map{/\S+/g}<STDIN>; $r=qr/$a/s} say "$ARGV - " . (/$r/?"PASS":"FAIL") ' f1 f2
echo "line1 line4" | perl -Mre=eval -0777ne 'INIT{-t and die; $a=join "",map qq[ (?{print"\\nTrying $_ - "}) (.*?(??{"$_"}) (?{print"pass"})) ],map{/\S+/g}<STDIN>; $r=qr/^$a/sx; print "\n\$r=qr$r\n\n"} print "\n# $ARGV"; print "\n".(/$r/?"PASS":"FAIL...
echo "line1 line4" | perl -Mre=eval -0777ne 'INIT{-t and die; $a=join "",map qq[ (?{print"\\nTrying $_ - "}) (.*?(??{"$_"}) (?{print"pass"})) ],map{/\S+/g}<STDIN>; $r=qr/^$a/sx} print "\n# $ARGV"; print "\n".(/$r/?"PASS":"FAIL")."\n\n"' f1 f2

# View optimizations done on a pattern.
perl -Mre=optimization -Mojo -E 'say r optimization qr/^abc/'

# A way to check if using a regular expression.
perl -Mre=is_regexp -E 'say is_regexp qr{}'
1
perl -Mre=is_regexp -E 'say is_regexp 123'


#############################################################
## Perl Modules - threads
#############################################################

# Error: This Perl not built to support threads
# Check if perl binary supports threads.
perl -V:useithreads
perl -MConfig -E 'say $Config{useithreads}'

# Simple thread example in perl
# Threads start running already with threads->create()
perl -Mthreads -le '@t=map threads->create(sub{print "Im #$_"}), 1..10; $_->join for @t'

# Simple thread example in perl
# Find the summation of 1 through 10
# Uses a shared variable between threads
perl -Mthreads -Mthreads::shared -le '$sum=0; share($sum); @t=map threads->create(sub{$sum += $_}), 1..10; print $_->join for @t; print "sum: $sum"'

# Aliases for threads->create.
perl -lMthreads -le '@t=map threads->new(sub{print $_}), 1..3; $_->join for @t'
perl -lMthreads -le '@t=map async(sub{print $_}), 1..3; $_->join for @t'
perl -lMthreads -le '@t=map threads->new(sub{print $_}), 1..3; $_->join for @t'

# If using a coderef, you must use threads->create.
perl -lMthreads -le '$sub = sub{ print "123" }; @t=map threads->new( $sub ), 1..3; $_->join for @t'

# If using a coderef, you must use threads->create (with arguments).
perl -lMthreads -le '$sub = sub{ print "@_" }; @t=map threads->new( $sub, $_ ), 1..3; $_->join for @t'

# Shared and non shared variables example
perl -lMthreads -Mthreads::shared -le '$a=$b=1; share($a); async(sub{$a++; $b++})->join; print "a=$a, b=$b"'

# Thread pitfall. $a can be either 2 or 3 (race condition)
perl -lMthreads -Mthreads::shared -le '$a=1; share($a); $_->join for map async(sub{my $foo=$a; $a=$foo+1}), 1..2; print "a=$a"'

# Allow only one thread to touch a variable at a time
# This will cause a "deadlock" where one thread requires a reourses
# locked by another thread and vice versa
perl -Mthreads -Mthreads::shared -le 'share $a; share $b; push @t, async(sub{lock $a; sleep 20; lock $b}); push @t, async(sub{lock $b; sleep 20; lock $a}); $_->join for @t'
#
# Alternate syntax 1
perl -Mthreads -le 'my $a :shared; my $b :shared; push @t, async(sub{lock $a; sleep 20; lock $b}); push @t, async(sub{lock $b; sleep 20; lock $a}); $_->join for @t'
#
# Alternate syntax 2
perl -Mthreads -le 'my $a :shared; my $b :shared; push @t, threads->create(sub{lock $a; sleep 20; lock $b}); push @t, threads->create(sub{lock $b; sleep 20; lock $a}); $_->join for @t'

# Thread safe queues. Passing data around
perl -Mthreads -MThread::Queue -le 'my $q=Thread::Queue->new; $t=async(sub{ print "Popped $d off the queue" while $d=$q->dequeue  }); $q->enqueue(12); $q->enqueue(qw/A B C/); sleep 1; $q->enqueue(undef); $t->join'

# Thread safe queues. Passing complex data around
perl -Mthreads -MThread::Queue -le 'my $q=Thread::Queue->new; $t=async(sub{ print "Popped @$d off the queue" while $d=$q->dequeue  }); $q->enqueue([1..3]); $q->enqueue([qw/A B C/]); sleep 1; $q->enqueue(undef); $t->join'

# Compute pi using parallel threading
time perl -Mthreads -Mthreads::shared -le 'share $sum; $M=100_000_000; $T=6; $h=1/$M; sub sum { my $s; my($from,$to)=@_; for($from..$to){ my $x=$h*($_-0.5); $s += 4/(1+$x**2)}; $s } sub split_by { my($max,$by)=@_; my $from=1; my @l; while($to<$max){ ...


#############################################################
## Perl Modules - CAM::PDF
#############################################################

# Example getting title fields from a pdf.
use CAM::PDF;
use e;
my $infile   = shift or die "\nSyntax: perl fill:pdf.pl my.pdf\n";
(my $outfile = $infile) =~ s/(?=\.pdf)/_filled/i;
my $doc      = CAM::PDF->new($infile) or die "$CAM::PDF::errstr\n";
say "Titles of the fields:";
p [$doc->getFormFieldList];
say "Adding new field values";
$doc->fillFormFields(
   Start_Date => "Value 1",
   Closed_Date => "Value 2",
   Closed_By => "Value 3",
);
say "saving new file";
$doc->cleanoutput($outfile);


#############################################################
## Perl Modules - Carp
#############################################################

# Show a stack trace in perl.
perl -MCarp=longmess -E 'sub fun1{ fun2("TO FUN2") } sub fun2{ say longmess } fun1("TO FUN1")'

# Show a stack trace in perl. (Carp uses a similar approach).
# @DB::args is set (for a scope) when this command is run (some magic).
{
   package DB;
   my @caller = caller($scope);
   () = caller($scope);             # Same thing (to invoke LIST context).
}
perl -E 'sub fun1{ fun2("TO FUN2") } sub fun2{ my $scope = 0; while(my @caller = caller($scope)){ {package DB; () = caller($scope)} say "@caller[1,2,3,4] - (@DB::args)"; $scope++ }} fun1("TO FUN1")'


#############################################################
## Perl Modules - Carton
#############################################################

# Keep track of the installed modules in a local directory by making a
# virtual environment. Like virtualenv and requirements.txt, but for Perl.
cpanm Carton

# Perl install modules found in cpanfile
carton install

# Perl zip modules found in cpanfile
carton bundle


#############################################################
## Perl Modules - CGI
#############################################################

cheats.txt  view on Meta::CPAN

], 'My' )

# New perl OO example (BUILD ADJUST phases)
perl -MObject::Pad -Mojo -E 'class My{ has $x :param; method Say { say "Say(): [@_] self=$self,x=$x"} BUILD { say "BUILD(): [@_]"; qw(x from_build) } sub BUILDARGS { say "BUILDARGS(): [@_]"; qw(x from_buildargs) } ADJUST { say "ADJUST(): [@_] self=$s...
BUILD(): [x from_buildargs]
ADJUST(): [HASH(0xb4000076ffc351f8)] self=My=ARRAY(0xb4000076ffc266d8)
Say(): [say input] self=My=ARRAY(0xb4000076ffc266d8),x=from_buildargs
bless( [
  "from_buildargs"
], 'My' )

# New perl OO example (ADJUST strict phases)
perl -MObject::Pad -Mojo -E 'class My :strict(params) { has $x :param; method Say { say "Say(): [@_] self=$self,x=$x"} ADJUST { say "ADJUST(): [@_] self=$self"; qw(x from_adjust) } } my $s = My->new(x => "new_arg", x2 => 2 ); $s->Say("say input"); sa...
ADJUST(): [HASH(0xb400007a337fa2c0)] self=My=ARRAY(0xb400007a337e76b8)
Unrecognised parameters for My constructor: x2 at -e line 1.


#############################################################
## Perl Modules - overload
#############################################################

# Perl Modules - overload example code.
pod Set::Scalar::Base -e


#############################################################
## Perl Modules - PadWalker
#############################################################

# View the lexical variables in a scope.
perl -MPadWalker=peek_my -Mojo -E 'my $var=123; say r peek_my(0)'
{
  "\$var" => \123
}

# Call a method of an object obtained from peek_my
perl -MDevel::Peek -MPadWalker=peek_my -Mojo -E '{ package My; sub Func {"My-Func"} } my $var =  bless {}, "My"; my $obj_ref = peek_my(0)->{q($var)}; Dump $var; Dump $obj_ref; say $$obj_ref->Func'

# Update a lexical variable in a different scope.
my $lexicals = peek_my(1);
$lexicals->{'@arr'}->[1] = 4;


#############################################################
## Perl Modules - PadWalker::Eval
#############################################################

# Idea for a new module to run eval at a specific scope.
perl -E 'my $v=1; {package My; my $v=2; sub run_code { my ($code) = @_; my $v=3; eval $code }} my $v=4, say My::run_code(q($v))'

# PadWalker::Eval ideas.
sub eval ($string, $scope_level=0)


#############################################################
## Perl Modules - Parallel::ForkManager
#############################################################

# Simple exmplae of parallel processing
# (Perl Modules - Parallel::ForkManager)
# About 3 times slower than using threads!!!
perl -MParallel::ForkManager -E '
    my $pm = Parallel::ForkManager->new(30);
    for my $file (1..30) {
        $pm->start and next;
        say "Processing file $file";
        sleep(1);
        $pm->finish;
    }
    $pm->wait_all_children;
'


#############################################################
## Perl Modules - PerlIO
#############################################################

# View the encoding layers applied to a filehandle.
perl -E 'say for PerlIO::get_layers(*STDOUT)'
unix
perlio
perl -C -E 'say for PerlIO::get_layers(*STDOUT)'
unix
perlio
utf8
perl -CO -E 'say for PerlIO::get_layers(*STDOUT)'
unix
perlio
utf8


#############################################################
## Perl Modules - Pod::Usage
#############################################################

# Pull out a section from pod
perl -MPod::Usage=pod2usage -E "pod2usage(-input => `perldoc -l ojo`, -verbose => 99, -sections => '.*/x');"

# Pull out a sectin of perl documentation and store it in a variable
perl -MPod::Usage=pod2usage -E "open my $fh, '>', \my $out or die $!; pod2usage(-input => `perldoc -l ojo`, -verbose => 99, -sections => '.*/x', -output => $fh, exitval => 'NOEXIT'); say qq([$out])"


#############################################################
## Perl Modules - POSIX
#############################################################

# Perl Modules - POSIX
# exit vs _exit
# exit calls DESTROY, whereas, _exit does not:
perl -MPOSIX=_exit -E 'sub A::DESTROY { say "DEST" } my $v = bless {}, "A"; exit(0)'
DEST
perl -MPOSIX=_exit -E 'sub A::DESTROY { say "DEST" } my $v = bless {}, "A"; _exit(0)'


#############################################################
## Perl Modules - Role::Tiny
#############################################################

# Light alternative to Mojo::Base -role
package My::Role;
use Role::Tiny;

cheats.txt  view on Meta::CPAN

perl6 -e 'say [\+] 1..5'

# Find the factorial of numbers
perl6 -e 'say [*] 1..5'

# Find the factorial of numbers (with intermediate steps)
perl6 -e 'say [\*] 1..5'

# Create factorial operator (!)
perl6 -e 'sub postfix:<!> {[*] 1..$^n}; say 5!'

# Create :=: operator (for sorting)
# Use rakudo-star-2017.01 for the interactive shell
perl6 -e 'sub infix:<:=:> ($a is rw, $b is rw) {($a,$b) = ($b,$a)}; my @a=(6,1,5); @a[0] :=: @a[1];  dd @a'

# Return first match (regex)
perl6 -e 'say ~$/ if "abc:def" ~~ /\w+/'

# Return all matches (regex)
perl6 -e 'say ~$/ if "abc:def" ~~ m:g/\w+/'

# Find largest prime factor (of n)
perl6 -e 'my $n=600_475_143; for 2,3,*+2...* {while $n %% $_ {$n div= $_; .say and exit if $_ > $n}}'

# Change named constructor into positional
perl6 -e 'class Point3D{has $.x; has $.y; has $!z; submethod BUILD(:$!x,:$!y,:$!z){say "Init"};  method get{$!x,$!y,$!z} }; my $a = Point3D.new(x=>23,y=>42,z=>2); .say for $a.get'

# Redefine/Create constructor for method new
perl6 -e 'class Point2D{has Numeric $.x; has Numeric $.y; method new($x,$y){$.bless(x=>$x,y=>$y)};  method get{$.x,$.y} }; my $a = Point2D.new(3,4); .say for $a.get'

# Run the debugger on a script
perl6debug sqrt.pl6

# Run the debugger on a one-liner
perl6debug -e '.say for 1..10'

# Debug a regular expression
perl6debug -e '"abc" ~~ /a(.+)c/

# Compare perl6 speeds (rakudo)
cd <RAKUDO_DIR>
perl6=`ls */perl6`
for p in $perl6 perl; do echo; echo "---------------------------------"; echo "$p"; time $p -e 'print join " ", grep /0/, (1..100)'; done
for p in $perl6 perl; do echo; echo "---------------------------------"; echo "$p"; time $p -e 'print 0.1 + 0.2 == 0.3'; done
echo


#############################################################
## Perlbrew
#############################################################

# Restore original perl environment
# https://stackoverflow.com/questions/25188575/switching-to-the-system-perl-using-perlbrew
perlbrew off           # only for this session (terminal)
perlbrew switch-off    # permanently

# Using the shebang line with perlbrew (-S to pass in args)
#!/usr/bin/env perl
#!/usr/bin/env -S perl -l

# Install with thread support.
perlbrew install perl-5.38.2 --thread

# Install multiple versions with and without thread support.
perlbrew install-multiple 5.38.2 blead --both thread
perlbrew switch perl-5.38.2-thread-multi
perl -V:'use.*thread.*'

# Upgrade current perl version.
perlbrew upgrade-perl

# Upgrade perlbrew
perlbrew self-upgrade
perlbrew version

# Upgrade cpanm
perlbrew install-cpanm

# Cleanup downloaded files.
perlbrew clean


#############################################################
## Performance Testing - General
#############################################################

# Performance Testing   - Ensures the system meets performance criteria like speed and responsiveness.
# Load Testing          - Checks system behavior under expected user load.
# Stress Testing        - Determines the system's breaking point by pushing it beyond normal capacity.
# Scalability Testing   - Assesses how well the system scales with increased workload.
# Spike Testing         - Examines how the system handles sudden spikes in load.
# Volume Testing        - Verifies system performance with varying amounts of data.


#############################################################
## PI - General
#############################################################

# No password when entering sudo commands (Linux,pi,debug)
vi /etc/sudoers
# Add this to bottom
pi 	ALL=(ALL) NOPASSWD:ALL

# No password when entering sudo commands (Linux,pi,debug)
sudo usermod -a -G GROUP_NAME USER
#
# Allow members of group sudo to execute any command
%sudo	ALL=(ALL:ALL) NOPASSWD:ALL

# autostart file location (pi)
sudo mount -o remount,rw /
vi /home/pi/.config/lxsession/LXDE-pi/autostart
sudo reboot

# Unable to write to /boot/config.txt (pi)
# Due to read only file system
# May need to mount a couple times (until "mount | grep boot" shows "rw")
sudo mount -o remount,rw /
sudo touch /forcefsck
sudo reboot


#############################################################
## PI - Configuration
#############################################################

# Get name of raspberry pi

cheats.txt  view on Meta::CPAN

#
# Step 4 – Download Required Jar Files:


# Create selenium service
#
sudo cp ~/my/git/srto/selenium/setup/_etc_systemd_system_selenium.service /etc/systemd/system/selenium.service
sudo vi /etc/systemd/system/selenium.service
+ [Unit]
+ Description=Selenium Server
+
+ [Service]
+ EnvironmentFile=-/etc/default/selenium
+ User=<USER>
+ Group=<USER>
+ Environment="PERL5OPT=-d:NYTProf" "NYTPROF='trace=0:start=no:addpid=1:slowops=0'"
+ Environment=DISPLAY=:1
+ ExecStart=/usr/bin/java -Dwebdriver.chrome.driver=/usr/bin/chromedriver -jar /usr/local/lib/selenium/current.jar $SELENIUM_OPTS
+ SuccessExitStatus=143
+
+ [Install]
+ WantedBy=graphical.target

# Selenium service environment file
#
sudo cp ~/my/git/srto/selenium/setup/_etc_default_selenium /etc/default/selenium
sudo vi /etc/default/selenium
+ SELENIUM_OPTS="-role standalone -debug"

# Enable selenium service (runs on login)
sudo systemctl enable selenium.service
sudo systemctl start selenium.service

# Run selenium test using curl (for debug)
curl -X POST http://localhost:4444/wd/hub/session -d '{ "desiredCapabilities": { "browserName": "chrome" } }'
curl -X POST http://localhost:4444/wd/hub/session -d '{ "desiredCapabilities": { "browserName": "firefox" } }'

# Type the Enter/Return key in Selenium.
perl -C -E 'say "\N{U+E007}"'   
perl -C -E 'say "\x{E007}"'     

# Make sure to use the apt firefox and not snap
# when seeing: Firefox profile not missing or not accessible.
sudo snap remove firefox
sudo add-apt-repository ppa:mozillateam/ppa
 echo '
Package: *
Pin: release o=LP-PPA-mozillateam
Pin-Priority: 1001
' | sudo tee /etc/apt/preferences.d/mozilla-firefox
echo 'Unattended-Upgrade::Allowed-Origins:: "LP-PPA-mozillateam:${distro_codename}";' | sudo tee /etc/apt/apt.conf.d/51unattended-upgrades-firefox


#############################################################
## SQLite3 Database
#############################################################

# Install sqlite on Unix (after in zipping the amalgamation file. make sure these 3 are present:
# shell.c, sqlite3.c, sqlite3.h). rename to a.out to sqlite3
# (database, sqlite3)
gcc shell.c sqlite3.c -lpthread -ldl

# View all the tables in a database (database, sqlite3)
sqlite3 my.db '.tables'

# Turn on column names on query results (database, sqlite3)
sqlite3 my.db '.explain on' 'select * from page_groups'

# Print database structure and data (database, sqlite3)
sqlite3 my.db '.dump'

# View current status/info (database, sqlite3)
sqlite3 my.db '.show'

# REFERENCES and FOREIGN KEYS are (database, sqlite3)
# used to ensure that the tables keys are valid since they
# are found in the foreign table.

# Output the results with a header and evenly spaced columns
sqlite3 my.db --header -column 'select * from my_table'

# Create a new database, table, and data (nathan)
sqlite3 my.db 'create table Users(name,date)'
sqlite3 my.db 'insert into Users values ("bob",20)'
sqlite3 my.db 'insert into Users values ("Joe",25)'
sqlite3 my.db '.explain on' '.width auto' 'select * from Users'

# Case Insensitive Search in SQL query
SELECT ... FROM ... WHERE ... ORDER BY name COLLATE NOCASE ASC LIMIT 5

# Master sqlite table (.tables)
if (table == "") {
    query = m_interface->prepare("SELECT name from sqlite_master");                         // .tables
}
# View the .schema
else if (haveVerbose) {
    query = m_interface->prepare("SELECT sql FROM sqlite_master WHERE name=:table");        // .schema
    query.bind(":table", table);
}
# View the columns
else {
    query = m_interface->prepare("SELECT name FROM PRAGMA_TABLE_INFO(:table)");             // column names
    query.bind(":table", table);

# Get all columns names from SQLite
sqlite3 my.db "PRAGMA table_info(myTable)"
#
sqlite3 my.db "SELECT name FROM pragma_table_info('myTable') ORDER BY name"

# Provide default for null values using COALESCE (sqlite3)
SELECT DISTINCT COALESCE(col,'NULL') FROM myTable ORDER BY col ASC

# SQLite if/else, concat(merge) columns(strings)
SELECT   name,
		 CASE WHEN var1 = 1 THEN 'x'  ELSE '-'  END ||
		 CASE WHEN var2 = 1 THEN '/x' ELSE '/-' END ||
		 CASE WHEN var3 = 1 THEN '/x' ELSE '/-' END ||
		 CASE WHEN var4 = 1 THEN '/x' ELSE '/-' END
		 AS var
FROM     myTable
ORDER BY name;

cheats.txt  view on Meta::CPAN

# Manually run openvpn.
cd ~/my/git/otrs/SETUP/vpn_setup/EasyRSA/pki/private
sudo openvpn --config vpn-otrs.conf


#############################################################
## VLC
#############################################################

# Install support for creating soft subtitles in vlc videos (mp4)
sudo apt install gnome-subtitles
rm -fr ~/.cache/gstreamer-1.0/*     # If error opennig file.
gnome-subtitles


#############################################################
## Vue - General
#############################################################

# Vue shorthand (shortcuts)
@click = v-on:click
:value = v-bind:value

# Check Vue version
npm v vue

# Create Vue CLI app
vue create vue-first-app

# Run Vue server (start)
cd vue-first-app
npm run serve
#
# The npm run commands can be found in:
package.json /"scripts":
#
# Defaut script commands:
serve
build
lint

# Missing Node modules folder
npm install

# Setup vue webpack (many files)
npm install --global vue-cli
vue init webpack

# Vue - Watch for changes to this.$refs
this.$watch(() => this.timerRef ? this.timerRef.timer.time : null, (newTime, oldTime) => {
    console.log('Watched time: ', newTime, oldTime);
    this.$refs.form.values.AccountedTime = newTime;
});


#############################################################
## WII
#############################################################

# Write files/games to WII.
https://mariokartwii.com/showthread.php?tid=121
https://www.gametdb.com/Wii/Search


#############################################################
## Windows Bugs
#############################################################

# Windows stuck in control mode (Tobias Wulf,windows bug)
Recovery: Most of the time, Ctrl + Alt + Del re-sets key status
to normal if this is happening. (Then press Esc to exit system screen.)
Another method: You can also press stuck key: so if you clearly see that
it is Ctrl which got stuck, press and release both left and right Ctrl .

# Why I have to press keys two times to get the ^ or ´ or ` (windows bug)
With this keyboard layout the ^ keystroke becomes a modifier to
enabling entering of special characters.
To get a single ^ character you will need to type ^+Space.


#############################################################
## Windows Command Prompt (DOS)
#############################################################

# Set an environmental variable (DOS)
setx <variable> <value>

# Unset an environmental variable (DOS)
setx <variable> ""

# Append path environmental variable (DOS)
setx path "new_dir_to_append"

# Change the width and height of a DOS window
mode con: cols=120 lines=20


#############################################################
## Windows - Drives
#############################################################

# Get mapped windows drives
net use

# Map windows drives
net use k: \\path /persistent:yes


#############################################################
## Windows - Excel
#############################################################

# Get last row in an excel column
=MATCH(TRUE,INDEX($K$3:$K$22="",0),0)-1

# Show excel formulas
Ctrl + `

# Insert the current date
Ctrl + :



( run in 0.948 second using v1.01-cache-2.11-cpan-c966e8aa7e8 )