App-Cheats
view release on metacpan or search on metacpan
# Enable exception handling. Generates extra code needed to propagate exceptions. For some targets,
# this implies GCC will generate frame unwind information for all functions, which can produce
# significant data size overhead, although it does not affect execution. If you do not specify this
# option, GCC will enable it by default for languages like C++ which normally require exception
# handling, and disable it for languages like C that do not normally require it. However, you may need
# to enable this option when compiling C code that needs to interoperate properly with exception
# handlers written in C++. You may also wish to disable this option if you are compiling older C++
# programs that don't use exception handling.
# -l library (gcc option,flag,order)
# Search the library named library when linking.
#
# "
# It makes a difference where in the command you write this option;
# the linker searches and processes libraries and object files in the order they are specified.
# Thus, foo.o -lz bar.o
# searches library z after file foo.o but before bar.o.
# If bar.o refers to functions in z, those functions may not be loaded.
# "
#
# Think: at this point what is needed?
# If its not needed by now it wont be loaded in (although it may be available)
# Problem: Seeing these errors
# undefined reference to ...
#
# Solution: Change order of libraries
#############################################################
## GDX
#############################################################
# Install gdx on termux.
pkg install ecj dx
cd ~/git
git clone https://github.com/ravener/libgdx-termux
cd libgdx-termux/
./fetch.sh
#############################################################
## Geb - General
#############################################################
# Geb manual
https://gebish.org/manual/current/
# Setup Geb (stuck)
#
# Go here
https://search.maven.org/
#
# Search and download these:
org.gebish:geb-core
org.seleniumhq.selenium:selenium-chrome-driver
org.seleniumhq.selenium:selenium-support
#
# Setup Geb (from repo,starting out)
cd D:\my\setup\geb\sample
git clone https://github.com/geb/geb-example-gradle
cd geb-example-gradle
gradlew chromeTest
#
# Install pip
D:\my\setup\pip\get-pip.py
#
# Install selenium
pip install selenium
# Using Python and Selenium (Geb)
#
cd D:\my\setup\geb\chromedriver_win32
ls
chromedriver.exe
sample.py
#
cat sample
import time
from selenium import webdriver
driver = webdriver.Chrome(r'D:\my\setup\geb\chromedriver_win32\chromedriver.exe') # Optional argument, if not specified will search path.
driver.get('http://www.google.com/');
time.sleep(5) # Let the user actually see something!
search_box = driver.find_element_by_name('q')
search_box.send_keys('ChromeDriver')
search_box.submit()
time.sleep(5) # Let the user actually see something!
driver.quit()
# Cannot click on a element when Geb Testing:
# Use this approach:
js.exec(0, "document.querySelectorAll('.rowlink')[arguments[0]].click();");
# Pause a Geb test (Groovy,Geb,Spock)
pause()
#
# Unpause by running this in the controled console:
geb.unpause = true
# Waiting in Geb tasting (Groovy,Geb,Spock,sleep,wait)
waitFor(3){} // 3 seconds
waitFor{} // some default time
Thread.sleep(3000) // 3 seconds
# Skip a test/function in Geb (Groovy,Geb,Spock)
import spock.lang.Ignore
@Ignore
def abc(){ }
# Run a single test with gradle in Geb (Groovy,Geb,Spock)
gradlew chromeTest -DchromeTest.single=My*
# Having given,when,and,then (Groovy,Geb,Spock)
# distinquish a regular function from a test function.
# Get the current url of the webpage (Groovy,Geb,Spock)
driver.currentUrl
getCurrentUrl()
# Another way to access elements that (Groovy,Geb,Spock)
# may return this error: StaleElementReferenceException
println(js.('document.title'))
println(js.('document.querySelector(".title").innerText'))
println(js.('document.querySelector("nav > a.active").innerText'))
return js.('document.querySelector(".title").innerText') =~ /NotSmart/
# Global debug variable (NotSmart Testing,Groovy,Geb,Spock)
# Ugly for now until a better way is found.
class Debug extends Module {
def debug = 0
}
//
if( (module(Debug)).debug ){
Thread.sleep(1000)
}
# Print to STDOUT (NotSmart Testing,Groovy,Geb,Spock)
println("var is $var")
// Maximize the chrome window (NotSmart Testing,Groovy,Geb,Spock)
def setupSpec() {
driver.manage().window().maximize()
}
# IntelliJ IDEA support for Gen Testing.
# - Download latest IDEA IDE (community edition)
https://confluence.jetbrains.com/display/IDEADEV/IDEA+2020.1+latest+builds
# - Update gradle/wrapper/gradle-wrapper.properties to use: gradle-6.5-bin.zip
# - Update IDEA settings
# - File -> Settings -> search: gradle
# View stack trace (not perfect since feature name is not shown)
// def getCurrentMethodName(){
//
// def marker = new Throwable()
//
// StackTraceUtils.sanitize(marker).stackTrace.eachWithIndex { e, i ->
// println "> $i ${e.toString().padRight(30)} ${e.methodName}"
// }
//
// // org.codehaus.groovy.runtime.StackTraceUtils.sanitize(new Exception()).printStackTrace()
//
// // def marker = new Throwable()
// // return StackTraceUtils.sanitize(marker).stackTrace[1].methodName
// }
#############################################################
## Golang
#############################################################
# Download go tour webpages locally.
go install golang.org/x/website/tour@latest
#############################################################
## Gradle
#############################################################
# Installing Grade (download,setup)
#
# Install a JDK:
https://www.oracle.com/java/technologies/javase-jdk14-downloads.html
#
# Setup Environment:
JAVA_HOME C:\Program Files\Java\jdk-14.0.1
JAVA_BIN C:\Program Files\Java\jdk-14.0.1\bin
JAVA_LIB C:\Program Files\Java\jdk-14.0.1\lib
#
# Install Gradle (Optional)
https://docs.gradle.org/current/userguide/installation.html
#
# Unzip and copy gradle-6.5 to:
cd C:\Gradle
#
# Setup Environment:
PATH_UNIX += C:\Gradle\gradle-6.5
GRADLE_HOME C:\Gradle\gradle-6.5
#
# Check that its setup:
gradle -v
#
# Sample build.gradle
task hello {
doLast {
println 'hello Gradle'
}
}
#
# Run using this command:
gradle hello
gradle -q hello
# Easiest way to setup Geb Testing with Gradle is to find a sample example.
geb-gradle-example-master
#############################################################
## Groovy
#############################################################
# Try groovy commands on the command line
groovysh
# Groovy replace all newlines and spaces with a single space
def text = $(query).eq(index).text().replaceAll(/\s+/, ' ')
# Groovy string to float
Float.parseFloat(string)
# Truthy-OR operator in Groovy (like defined-OR)
return Float.parseFloat(old ?: '0.0')
#
# Like this in perl:
$old || '0.0'
# Defined-OR operator in Groovy (like defined-OR)
num ?= 0
#
# Like this in perl:
$old //= '0.0'
# Mimic keyboard input (Groovy,Geb Testing)
$("[name='${name}']") << value.toString()
# Groovy split, map, join
groovy -e "def ids = 'id1, id2'; println(ids.split(/,\s*/).collect({ return '#$it' }).join(', '))"
#
# Same thing in perl
perl -le "$ids = 'id1, id2'; print join ', ', map {qq(#$_)} split(/,\s*/, $ids)"
## H
#############################################################
## IAM - Helm
#############################################################
# Apply a patch file (-p1 ignore first later)
patch -p1 < ../test.patch
# Fix: "sh: -c: line 0: syntax error near unexpected token `('"
system qq(/bin/bash -c "diff -u <(echo a) <(echo b)");
system qq(/bin/bash -c "diff -u <(echo \\"a a2 a3\\") <(echo \\"b b2 b3\\")");
#############################################################
## Linux Commands - dos2unix
#############################################################
# Fix files endings of all files in folder (recursive)
find . -type f -print0 | xargs -0 dos2unix
# Convert newlines to unix format (trim off carriage returns, like dos2unix)
perl -lpe 'BEGIN{$n=chr 13; $r=qr/$n$/} s/$r//'
#############################################################
## Linux Commands - dpkg
#############################################################
# Print dpkg architecture (DES,machine)
# When installing packages.
dpkg --print-architecture
# Print allowed foreign architectures (DES,machine)
# When installing packages.
dpkg --print-foreign-architectures
# Error - Could not get lock /var/lib/dpkg/lock (admin)
sudo kill -9 $(sudo lsof | grep /var/lib/dpkg/lock | awk '{print $2}')
sudo dpkg --configure -a
# dpkg: error: dpkg status database is locked by another process (DES,bench)
sudo rm -f /var/lib/dpkg/lock
# Install a package from a file
sudo dpkg -i my.deb
# View packages installed on the system
dpkg -l
# Check if a package is installed on a system
dpkg -l | grep kate
# Check installion location of a package
dpkg -L <package>
# Add architecture to the list of architectures for which (DES)
# packages can be installed without using --force-architecture
dpkg --add-architecture i386
# Check if a package is on hold (no updates)
dpkg --get-selections apksigner
apt-mark showhold
# Remove packages marked with rc:
dpkg -l | \grep '^rc' | nth 1 | xargs sudo dpkg --purge
#############################################################
## Linux Commands - dmesg
#############################################################
# View kernel messages
dmesg
#############################################################
## Linux Commands - du
#############################################################
# Get top 20 people using too much disk space
du -ms /* | sort -nr | head -n 20
# Find how much space each locked user is using
a=`sudo passwd -Sa | AND -r "\bL$" | get_nth 0 | while read u; do ls -d1 /net/home*/$u; done 2>/dev/null | col_2_row`
b=`sudo du -scm `echo $a` | sort -nr`
echo "$b" | perl -ple '($u)=m{/([^/]+)$} or ($_=sprintf "%-30s %s", $_,"Password Status (L - Locked)") and next; ($s)=(split " ",`sudo passwd -S $u`)[-1]; chomp $s; $_ = sprintf "%-30s %s", $_, $s'
# Find how much space each locked user is using (compact)
sudo passwd -Sa | AND "\bL$" | perl -aple '$d=qx{sudo du -sm /net/home*/$F[0]}; $d = $? ? "NO HOME DIR" : (chomp $d,$d); $_ = "$d - $_"'
#############################################################
## Linux Commands - eval
#############################################################
# Variable name is stored in another variable
n1=abc
abc=blue
abc2=green
eval var=\$$n1
echo $var
n1=abc2
eval var=\$$n1
echo $var
# Expand $HOME variable (dollar,bash)
file='$HOME/my_path'
"`eval echo $file`"
# Expand uicfg $HOME variables
cat $HOME/uicfg | while read line; do echo `eval echo $line`; done
#############################################################
## Linux Commands - expect
#############################################################
# Run a command where user input is required (script,auto,password)
expect -c 'spawn ssh SOME_USER@irkdes "date"; expect "password:"; send "asdf1234\r"; interact'
# Expect quirks (scipt,auto,password)
# This will NOT work
echo "SOME_USER" | while read n; do expect ... ; done
# This DOES work
for n in "SOME_USER"; do expect ... ; done
# I had to do as root:
firewall-cmd -add-port=8089/tcp --permanent
# View firewall rules.
iptables -L
#############################################################
## Linux Logging
#############################################################
# View the error log for puppet
cat /var/log/syslog
#############################################################
## Linux Mounting
#############################################################
# Check paths to file servers
mount
# Fix Stale NFS on a file server. home4 down. cannot access
sudo umount -lf /net/home4
# should automount in a few secs
/etc/init.d/autofs restart # Otherwise, restart manually
/etc/init.d/nfs-common restart # Do both
# Change path to file server.
sudo vi /etc/auto.pw # edit OLD to NEW
sudo service autofs reload # reload auto mounting (only on higher benches)
sudo /etc/init.d/autofs restart
sudo /etc/init.d/autofs reload
# Get copy of latest auto loader server file
sudo \cp /home3/SOME_USER/auto.pw /etc/auto.pw
sudo /etc/init.d/autofs reload
# Setup puppet to change path to file server
sudo vi /etc/puppet/modules/autofs/files/auto.pw
sudo /etc/init.d/autofs reload
#############################################################
## Linux Software
#############################################################
# Which OS version are we using (DES,Ubuntu 22.04)
lsb_release -a
# Find out if using 32 or 64 bit linux system
uname -m # 32 is i686 or i386, 64 is x86_64
# Find out the release name (UI,bench,DES)
lsb_release -a
# Show which debian version name machine is (such as wheezy) (Added: 2017-10-05 11:26:48 AM)
lsb_release -cs
# Get name of our OS:
cat /etc/os-release | \grep '^ID='
ID="centos"
#############################################################
# Linux Startup
#############################################################
# Prevent a program from starting on Ubuntu during boot.
# Click on âStartup Applicationâ and launch Startup Program Preference.
#############################################################
## Linux Swap Memory
#############################################################
# Create swap memory file
#
mkdir /media/fasthdd
dd if=/dev/zero of=/media/fasthdd/swapfile.img bs=512 count=1M
#
# Turn that swap file into a filesystem !?
mkswap /media/fasthdd/swapfile.img
chmod 600 /media/fasthdd/swapfile.img
#
# Add this line to /etc/fstab to be able to use the swap at startup
/media/fasthdd/swapfile.img swap swap sw 0 0
#
# Activate the swap file
swapon /media/fasthdd/swapfile.img
#
# Deactivate the swap file
swapoff /media/fasthdd/swapfile.img
# View swap memory
cat /proc/swaps
top
#############################################################
## Ansible
#############################################################
# Install ansible prerequisites (on lnxbr42)
sudo apt-get install vagrant virtualbox
# Install ansible
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 123456
sudo apt-get update
sudo apt-get install ansible
#############################################################
## Bash - General
#############################################################
# See max expansion of *
getconf ARG_MAX # 2097152
# Run a bash command without using a file
bash -c 'echo abc'
# my $data=<<HERE;
# Data1
# Data2
# START
# skip
# ok1
# ok2
# STOP
# Data3
# Data4
# START
# ok3
# ok4
# STOP
# Data5
# HERE
#
# my $ways = {
# normal => sub {
# $data =~ s{ ( ^ \s* START \n skip .+? STOP \s* ) }{}xmsgr,
# },
# eval => sub {
# $data =~ s{ ( ^ \s* START .*? STOP \s* \n ) }{
# local $_ = $1;
# /skip/ ? "" : $_;
# }xmsger,
# },
# };
#
# cmpthese( 3_000_000, $ways);
# Interpolation vs concat comparison:
#
# No assignment.
perl -Me -e 'my $v = 123; n { interp => sub { "$v" }, concat => sub { $v } }, 10000000'
#
Rate interp concat
interp 29411765/s -- -91%
concat 333333333/s 1033% --
#
# Full assigned.
perl -Me -e 'my $v = 123; n { interp => sub { my $c = "$v"}, concat => sub { my $c = $v } }, 10000000'
Rate interp concat
interp 12195122/s -- -68%
concat 38461538/s 215% --
#
# Inside a sentence.
perl -Me -e 'my $v = 123; n { interp => sub { my $c = "I got $v dollars"}, concat => sub { my $c = "I got " . $v . " dollars" } }, 10000000'
Rate interp concat
interp 14285714/s -- -4%
concat 14925373/s 4% --
# Interpolation vs concat vs comma comparison:
perl -Me -e 'my $v = 123; n { interp => sub { "I got $v dollars"}, concat => sub { "I got " . $v . " dollars" }, comma => sub{ "I got ", $v, " dollars" } }, 10000000'
Rate interp concat comma
interp 20408163/s -- -2% -57%
concat 20833333/s 2% -- -56%
comma 47619048/s 133% 129% --
# Remove duplicate characters.
perl -E '$_ = "abbbc"; s/(.)\g1+/$1/; say'
abc
perl -E '$_ = "abbbc"; tr///cs; say'
abc
# Remove duplicate characters (benchmark).
perl -Me -e '
$copy = "abbc";
n {
s => sub{
local $_ = $copy;
s/(.)\g1+/$1/;
$_;
},
tr => sub{
local $_ = $copy;
tr///cs;
$_;
}
}, 1000000
'
(warning: too few iterations for a reliable count)
Rate s tr
s 1408451/s -- -70%
tr 4761905/s 238% --
# Comparing different ways in perl to combine hashes.
#
# Each: 2.6s
while ( my ($key,$val) = each %users_one ) {
$users{$key} = $val;
}
#
# Merge: 1.7s
%users = ( %users, %users_one);
#
# Slice: 700ms
@users{keys %users_one} = values %users_one;
# Benchmark glob() vs -e() functions
perl -Me -e '
n {
e_found => sub{ -e "recursive.pl" },
e_not_found => sub{ -e "recursive2.pl" },
glob_found => sub{ glob "recursive.pl" },
glob_not_found => sub{ glob "recursive2.pl" },
glob_wild_flag_found => sub{ glob "rec*.pl" },
glob_wild_flag_not_found => sub{ glob "rec2*.pl" },
}, 1_000_000
'
Rate glob_wild_flag_not_found glob_wild_flag_found glob_found glob_not_found e_found e_not_found
glob_wild_flag_not_found 79491/s -- -45% -94% -95% -96% -98%
glob_wild_flag_found 143885/s 81% -- -90% -91% -93% -96%
glob_found 1408451/s 1672% 879% -- -15% -35% -56%
glob_not_found 1666667/s 1997% 1058% 18% -- -23% -48%
e_found 2173913/s 2635% 1411% 54% 30% -- -33%
e_not_found 3225806/s 3958% 2142% 129% 94% 48% --
#############################################################
## Perl Binary
#############################################################
# Convert to binary using recursion (POC,perl).
sub binary{
my($n) = @_;
$n //= $_;
return $n if $n == 0 or $n == 1;
my $k = int($n/2);
my $b = $n % 2;
binary($k) . $b;
}
# applicable in the first place.
#
# In fact, if the engine checks to see if an
# optimization is applicable and the answer is
# âno,â the overall result is slower because it
# includes the fruitless check on top of the
# subsequent normal application of the regex.
#
# So, thereâs a balance among how much time an
# optimization takes, how much time it saves,
# and importantly, how likely it is to be invoked.
# Perl Regular Expressions - Best Practices
# Say what you mean
# The problem is that the first.+" matches past
# the backslash, pulling it out from under the
# (\\ \n.+)+" that we want it to be matched by.
#
# Well, hereâs the first lesson of the chapter:
# if we donât want to match past the backslash,
# we should say that in the regex.
#
# We can do this by changing each dot to:
[Ë\n \\].
#############################################################
## Perl Regular Expressions - Bugs
#############################################################
# Perl Regular Expressions - Bugs
# // means to mast the last successive pattern.
# If none, then would match empty.
# Explicitly use /(?:)/ for empty instead.
# https://perldoc.perl.org/perlop#The-empty-pattern-//
#
# Avoid using single variable directly in regex (like $want below):
perl -E '$want = ""; say "Found: $1" if "catnip" =~ /(...)/i; say "Found again: $1" if "dognip" =~ /$want/; say ${^LAST_SUCCESSFUL_PATTERN}'
Found: cat
Found again: dog
(?^ui:(...))
#
# Better to use qr{}:
perl -E '$want = qr{}; say "Found: $1" if "catnip" =~ /(...)/i; say "Found again: $1" if "dognip" =~ /$want/; say ${^LAST_SUCCESSFUL_PATTERN}'
Found: cat
Found again:
(?^u:)
#############################################################
## Perl Regular Expressions - Captures
#############################################################
# Perl Regular Expressions - Captures
Some examples:
/(\d)(\d)/ # Match two digits, capturing them into $1 and $2
/(\d+)/ # Match one or more digits, capturing them all into $1
/(\d)+/ # Match a digit one or more times, capturing the last into $1
# Perl Regular Expressions - Captures
# To avoid this ambiguity, refer to a capture group by its number using \g{NUMBER}, and to an octal character by number using \o{OCTNUM}.
# So \g{11} is always the 11th capture group, and \o{11} is always the character whose codepoint is octal 11
# Perl Regular Expressions - Captures
# branch reset
m{
(?|
(\d+) \s+ (\pL+) # these are $1 and $2
|
(\pL+) \s+ (\d+) # and so is this pair!
)
}x
#############################################################
## Perl Regular Expressions - Character Classes
#############################################################
# Perl recognizes the following POSIX character classes ([[:ascii:]]):
# https://perldoc.perl.org/perlrecharclass#POSIX-Character-Classes
#
alpha Any alphabetical character (e.g., [A-Za-z]).
alnum Any alphanumeric character (e.g., [A-Za-z0-9]).
ascii Any character in the ASCII character set.
blank A GNU extension, equal to a space or a horizontal tab ("\t").
cntrl Any control character. See Note [2] below.
digit Any decimal digit (e.g., [0-9]), equivalent to "\d".
graph Any printable character, excluding a space. See Note [3] below.
lower Any lowercase character (e.g., [a-z]).
print Any printable character, including a space. See Note [4] below.
punct Any graphical character excluding "word" characters. Note [5].
space Any whitespace character. "\s" including the vertical tab ("\cK").
upper Any uppercase character (e.g., [A-Z]).
word A Perl extension (e.g., [A-Za-z0-9_]), equivalent to "\w".
xdigit Any hexadecimal digit (e.g., [0-9a-fA-F]). Note [7].
# Compare perl regular expresion character classe styles.
#
[[:...:]] ASCII-range Full-range backslash Note
Unicode Unicode sequence
-----------------------------------------------------
alpha \p{PosixAlpha} \p{XPosixAlpha}
alnum \p{PosixAlnum} \p{XPosixAlnum}
ascii \p{ASCII}
blank \p{PosixBlank} \p{XPosixBlank} \h [1]
or \p{HorizSpace} [1]
cntrl \p{PosixCntrl} \p{XPosixCntrl} [2]
digit \p{PosixDigit} \p{XPosixDigit} \d
graph \p{PosixGraph} \p{XPosixGraph} [3]
lower \p{PosixLower} \p{XPosixLower}
print \p{PosixPrint} \p{XPosixPrint} [4]
punct \p{PosixPunct} \p{XPosixPunct} [5]
\p{PerlSpace} \p{XPerlSpace} \s [6]
space \p{PosixSpace} \p{XPosixSpace} [6]
upper \p{PosixUpper} \p{XPosixUpper}
word \p{PosixWord} \p{XPosixWord} \w
xdigit \p{PosixXDigit} \p{XPosixXDigit} [7]
# Perl Regular Expressions - Character Classes
# In perl these are the meanings of these backslash classes:
#
# ASCII Range:
$reg1 = qr{
(?{ say $num })
(??{ $num })
}x;
$num = 222;
$reg2 = qr{
(?{ say $num })
(??{ $num })
}x;
}
my $regex = qr{ $reg1 $reg2 }x;
say "222222" =~ /$regex/
'
222
222
1
#############################################################
## Perl Regular Expressions - Extended - $^R
#############################################################
# Perl Regular Expressions - Extended - $^R
# Example of using $^R to store sub matches.
perl -Me -e '$_ = "One fish two fish really red fish blue fish"; say "Before: ", $^R // "undef"; { local $^R = []; / ^ (?> \s*+ (?> (?<name>\w+) \s+ fish (?{ [ $^R->@*, $+{name} ] }) | (?: (?! \b fish \b ) . )*+ fish ) )+ /xg; p $^R; p \%+; p \%- }; ...
Before: undef
[
[0] "One",
[1] "two",
[2] "blue",
]
{
name => "blue",
} (tied to Tie::Hash::NamedCapture)
{
name => [
[0] "blue",
],
} (tied to Tie::Hash::NamedCapture)
After: undef
# Perl Regular Expressions - Extended - $^R
# Failure reverts changes to scoped variables.
perl -Me -e '$_ = "One fish two fish really red fish blue fish"; say "Before: ", $^R // "undef"; { local $^R = []; / ^ (?> \s*+ (?> (?<name>\w+) \s+ fish (?{ [ $^R->@*, $+{name} ] }) | (?: (?! \b fish \b ) . )*+ fish ) )+ (*F) /xg; p $^R; p \%+; p \%...
Before: undef
[]
{} (tied to Tie::Hash::NamedCapture)
{} (tied to Tie::Hash::NamedCapture)
After: undef
#############################################################
## Perl Regular Expressions - Lookaround
#############################################################
# variable length lookaround in any PCRE
# http://www.drregex.com/2019/02/variable-length-lookbehinds-actually.html?m=1
perl -E 'say "ABXXXCD" =~ /(?<=X+)/'
Lookbehind longer than 255 not implemented in regex m/(?<=X+)/ at -e line 1.
#
# Workaround:
perl -E '$r = qr/ (?=(?<a>[\s\S]*)) (?<b> X++ (?=\g{a}\z) | (?<= (?= x^ | (?&b) ) [\s\S] ) )/x; say "ABXXXCD" =~ $r'
perl -E '$r = qr/ (?=(?<a>(?s:.*))) (?<b> X++ (?=\g{a}\z) | (?<= (?= x^ | (?&b) ) (?s:.) ) )/x; say "ABXXXCD" =~ $r'
CD
#
# Explanation:
(?=(?'a'[\s\S]*)) # Capture the rest of the string in "a"
(?'b'
X(?=\k'a'\z) # Match X followed by the contents of "a" to ensure
# the emulated lookbehind stops at the correct point.
| # OR
(?<= # Look behind (one character) match either:
(?=
x^ # A contradiction; non-empty to appease the nanny
| # OR
(?&b) # Recurse (match X OR look behind (one character)) etc..
)
[\s\S] # How far we go back each step: one single character
)
)
# Lagging split using a lookaround.
perl -E 'say for "1234567890" =~ /(?=(...))/g'
123
234
345
456
567
678
789
890
# Lagging split using a lookaround into a table format.
perl -E '@a = "1234567890" =~ /(?=(..))/g; say for map { $a[$_+2] ? "@a[$_..$_+2]" : () } 0..$#a'
12 23 34
23 34 45
34 45 56
45 56 67
56 67 78
67 78 89
78 89 90
# Perl Regular Expressions - Lookaround
# Mimicking atomic grouping with positive lookahead.
# Itâs perhaps mostly academic for flavors that
# support atomic grouping, but can be quite useful
# for those that donât: if you have positive
# lookahead, and if it supports capturing
# parentheses within the lookahead (most flavors
# do, but Tclâs lookahead, for example, does not),
# you can mimic atomic grouping and possessive
# quantifiers.
#
# (?>regex) can be mimicked with (?=(regex))\1.
# For example, compare these:
Ë(?>\w+):
Ë(?=(\w+))\1:
#############################################################
## Perl Regular Expressions - Loops
#############################################################
$AGE = 21;
$_ = q(I am $AGE years old);
s/(\$\w+)/$1/eeg;
say;
'
I am 21 years old
#############################################################
## Perl Regular Expressions - Parenthesis
#############################################################
# Perl Regular Expressions - Match Parenthesis
local $_ = 'foo(bar(this), 3.7) + 2 * (that - 1)';
my $r = qr {
(?&LOOP)
(?(DEFINE)
(?<LOOP>
\(
(?> [^()] | (?&LOOP) )*
\)
)
)
}x;
while (/\b (\w+ \s* ($r)) /x){
say $1;
$_ = $2;
}
#############################################################
## Perl Regular Expressions - Sets
#############################################################
# Any number but 5 (regex sets,char class).
# https://perldoc.perl.org/perlrecharclass#Extended-Bracketed-Character-Classes
perl -E 'say for map { "$_: " . /^ (?[ \d - [5] ])+ $/x } qw/ 12 15 18 /'
perl -E 'say for map { "$_: " . /^ [0-46-9]+ $/x } qw/ 12 15 18 /'
perl -E 'say for map { "$_: " . (/^\d+$/ && !/5/) } qw/ 12 15 18 /'
12: 1
15:
18: 1
#############################################################
## Perl Regular Expressions - Subpatterns
#############################################################
# Create a subpattern using:
# (?(DEFINE)
# (?<name>pattern)
# )
# It is recommended that for this usage you put the DEFINE
# block at the end of the pattern, and that you name any
# subpatterns defined within it.
#
# Then use it like:
# (?&name)
#
# Example:
perl -E '"look mk" =~ / (l (?&same_char) )k \s (.)k (?(DEFINE) (?<same_char> (.) \g{-1} ) ) /x; say "got: 1:$1, 2:$2, 3:$3, 4:$4"'
# Check for existence of a capture group.
# Can use either:
# - ({ exists $+{var} })
# - (?<var>IF|ELSE)
perl -E '
"abc" =~ /
(?{ say exists $+{var} ? 1 : 0 })
(?(<var>)
(?{ say "if" })
| (?{ say "else" })
)
(?<var> . )
(?{ say exists $+{var} ? 1 : 0 })
(?(<var>)
(?{ say "if" })
| (?{ say "else" })
)
/x
'
0
else
1
if
#############################################################
## Perl Regular Expressions - Verbs
#############################################################
# Perl regex verbs shoukd be benchmarked before
# being used since the additional compilation time
# might not justify the performance improvement.
# Great place to learn more about backtracking control verbs in regex.
# https://www.rexegg.com/backtracking-control-verbs.html
# Perl regex verb - ACCEPT (example)
perl -E '"0aaab" =~ / (?{ say pos . ":" }) 0* a+ (*ACCEPT) b? (?{ say " $&" }) (*FAIL) /x'
0:
# Perl regex verb - FAIL
# (?=^) matches after a newline.
perl -MEnglish -E 'qq(Aa\nBb\nCc) =~ / (?=^) (?{ say "|$PREMATCH<$MATCH>$POSTMATCH|\n" }) (*F) /smx'
# Perl regex verb - FAIL (example)
# Show all matches.
# Show when shifting position.
perl -E '"0aaab" =~ / (?{ say pos . ":" }) 0* a+ b? (?{ say " $&" }) (*FAIL) /x'
0:
0aaab
0aaa
0aa
0a
1:
aaab
aaa
aa
a
2:
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
cat /sys/firmware/devicetree/base/model
Raspberry Pi 3 Model B Plus Rev 1.3
# Check pi revision
cat /proc/cpuinfo
Code Model Revision RAM Manufacturer
a020d3 3B+ 1.3 1GB Sony UK
#
# Compare to:
https://www.raspberrypi.org/documentation/hardware/raspberrypi/revision-codes/README.md
# Find out the total on a linux machine (pi)
local ram=$(\grep MemTotal /proc/meminfo | perl -lne '($kb)=/(\d+)/; printf "%0.2fGB", $kb/1024/1024')
#############################################################
## PI - Network Interface
#############################################################
# Turn interface card off and on. (pi)
# Useful in cases where connection needs to be reset.
sudo ifconfig eth0 down && sudo ifconfig eth0 up
# Add a static IP address in Linux (pi,debug,Workarounds)
# Workaround for when DHCP does not work with the firewall
su # super user mode
mount -o remount,rw / # mount the filesystem
vi /etc/network/interfaces # update interfaces
auto eth0 # Add these lines
iface eth0 inet static
address 172.17.17.10
netmask 255.255.255.0
gateway 172.17.17.1
/etc/init.d/networking restart # restart the service
vi ~/webpage.sh
#IP=$(dhcpcd --dumplease eth0 | grep routers | cut -d\' -f2)
IP=172.17.17.1
reboot
#
The different keywords have the following meaning: (pi,debug,interfaces)
auto: the interface should be configured during boot time.
iface : interface
inet: interface uses TCP/IP networking.
#############################################################
## PI - Options
#############################################################
# Reduce blinking (pi)
sudo vi /boot/config.txt
/ hdmi_mode=82 # Original
# https://elinux.org/RPiconfig
82 1080p 60Hz Original
83 1600x900 Reduced blanking. Too small. Must scroll, plus keyboard is mostly gone)
84 2048x1152 Reduced blanking. Double size. Unreadable
85 720p 60Hz Good. But need to scroll
# Smart toggle (enable/disable) mouse cursor (pi)
# Remove/add "-nocursor" to this line:
# MUST first mount / then restart
sudo mount -o remount,rw /
sudo vi /etc/lightdm/lightdm.conf
/ xserver-command=X -nocursor
sudo reboot
#############################################################
## PI - Shortcuts
#############################################################
# Open Terminal on Linux (pi)
Control + Alt + T
( run in 1.502 second using v1.01-cache-2.11-cpan-d01c6094234 )