App-Cheats

 view release on metacpan or  search on metacpan

cheats.txt  view on Meta::CPAN


# 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:
//		#include <stdio.h>
//		#include <stdlib.h>
//		#include <string.h>
//
//		int main(int argc, char ** argv){
//			char * str;
//
//			if (argc>1) {
//				str = (char *) malloc(10);
//			}
//
//			printf("Str: %s\n",str);
//			free(str);
//
//			return 0;
//		}
//
// MAKE.bat
g++ my.c -o my.exe

# Try Catch in Cpp
# No throw means no catch
//
#include <iostream>
using namespace std;
int main(int,char**){
	int n = 10;
	int m = 0;
	try {
		// if( m == 0 ) throw "Division by zero condition!";
		int val = n / m;
		cout << "Divided: " << val << endl;
	}
	catch (...){
		cout << "Caught error" << endl;
	}
	cout << "DONE" << endl;
	return 0;
}

# Nested Try Catch in Cpp
# No throw means no catch
//
#include <iostream>
using namespace std;
int main(int,char**){
	int n = 10;
	int m = 0;
	int val;
	try {
		try {
			if( m == 0 ) throw "Division by zero condition!";
			val = n / m;
			cout << "Divided: " << val << endl;
		}
		catch (runtime_error& e){ cout << "Caught inner error1" << endl; }
		catch (out_of_range& e) { cout << "Caught inner error2" << endl; }
	}
	catch (...){ cout << "Caught outer error" << endl; }
	cout << "DONE" << endl;
	return 0;
}


#############################################################
## C,CPP - File Handles
#############################################################

# Open a file in CPP. This ensures the file exists.
MY_FILEHANDLE.open(SMART_FILE_PATH, std::ios::in | std::ios::out | std::ios::app);
MY_FILEHANDLE.close();
MY_FILEHANDLE.open(SMART_FILE_PATH, std::ios::in | std::ios::out);


#############################################################
## C,CPP - Header Files
#############################################################

# Missing sys/cdefs.h header file (DES,library)
sudo apt-get install libc6-dev-i386

# Missing curses.h 32 bit (DES,library)
sudo apt-get install lib32ncurses5-dev

# Missing readline/history.h header file (DES,library)
sudo apt-get install libreadline-dev

# Missing libelf.h header file (DES,library)
sudo apt-get install libelf-dev libelfg0

# Missing dwarf.h header file (DES,library)
sudo apt-get install libdwarf-dev

# Missing y.tab.h header file (DES,library)
sudo apt-get install byacc bison flex


#############################################################
## C,CPP - Functions
#############################################################

# Define a pure virtual function (OMS,cpp)
# It must be overriden/inherited in a derived class
virtual void func( int option, int count, int start_bit, int end_bit) = 0;


#############################################################
## C,CPP - Map
#############################################################

# std::map to std::string conversion in cpp
std::string column_names_new = "";

cheats.txt  view on Meta::CPAN

Embeds text with a right-to-left directional override.
---
POP DIRECTIONAL FORMATTING (U+202C)
Resets the directionality to the surrounding context.
---
LEFT-TO-RIGHT OVERRIDE (U+202D)
Forces text to be displayed left-to-right, overriding the
surrounding context.
---
RIGHT-TO-LEFT OVERRIDE (U+202E)
Forces text to be displayed right-to-left, overriding the
surrounding context.

# zero-width Unicode characters example.
perl -C -E 'say "<!START_\N{ZERO WIDTH SPACE}A\N{LEFT-TO-RIGHT MARK}B\N{RIGHT-TO-LEFT MARK}C\N{ZERO WIDTH NON-JOINER}-->"'
# Output:
<!START_​A‎B‏C‌-->

# Zero-width example of hiding text in a text area (plain text,POC)
perl -C -Me -E 'sub _BuildMark{ unpack("B*", "<!$_[0]-->") =~ tr/01/\N{ZERO WIDTH SPACE}\N{LEFT-TO-RIGHT MARK}/r } my $B = join "", _BuildMark("START_ABC"), "Line1: Ok\nLine2: NOk", _BuildMark("END_ABC"); say $B; d $B'
Line1: Ok
Line2: NOk

# Zero-width example of hiding text in a text area (plain text, POC, WIP)
perl -C -Me -E 'sub _BuildMark{ unpack("B*", "<!$_[0]-->") =~ tr/01/\N{ZERO WIDTH SPACE}\N{LEFT-TO-RIGHT MARK}/r } sub _ContainsMark { index(shift, _BuildMark(shift)) != -1 } $_ = join "", "Before\n", _BuildMark("START_ABC"), "Line1: Ok\nLine2: NOk",...


#############################################################
## HTML - Validation
#############################################################

# Input element validation in html (check,regex)
<input name="NAME" type="number" placeholder="?" step="any" class="value" style="grid-column: 5 / 6; grid-row: 2 / 3;" value="4.000">
<input name="name" type="text" pattern="^[-\wÄäÖöÜü\.,_]+$" value="VALUE">


#############################################################
## Java
#############################################################

# Compile a java program (script)
javac hello.java

# Run a java program (execute script)
java hello


#############################################################
## Javascript - General
#############################################################

# Efficient way in javascript to insert text as html (append to body)
document.querySelector('#id').insertAdjacentHTML('beforeEnd', to_add)
# (works fast, but script tags are not usable).
#
# Use this to allow using script tags
$(id).append(details_rc);

# Stack trace in javascript (js).
try {
    // Code throwing an exception
    throw new Error();
} catch(e) {
    console.log(e.stack);
}

# Javascript log function wrapper.
log (...args) {
    const verbose = false;
    if (verbose) {
        console.log(`[${this.name}]`, ...args);
    }
},


#############################################################
## Javascript - Ajax
#############################################################

# Javascript loaded in via ajax is not automatically executed.

# AJAX Javascript Example
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "ajax_info.txt", true);
  xhttp.send();
}

# AJAX Javascript Example (simpler)
# 'onload' is newer and a replacement for 'onreadystatechange' with the state check
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onload = function() {                       // <== Difference
     document.getElementById("demo").innerHTML = this.responseText;
  };
  xhttp.open("GET", "ajax_info.txt", true);
  xhttp.send();
}

# Submit a form using ajax. (prevents auto reload)
function save_details(endpoint) {
    console.log("POST ", endpoint);
    const form  = document.querySelector("form[id=details]");
    const xhttp = new XMLHttpRequest();
    xhttp.open("POST", endpoint);
    xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhttp.send( $("#details").serialize() );
}


#############################################################
## Javascript - Attributes
#############################################################

# Set/Get meta data for an HTML element
form = document.querySelector("form[id=details]");
form.setAttribute('_meta', "my_meta")

cheats.txt  view on Meta::CPAN

#############################################################

# Catch Control-C
perl -lE '$SIG{INT}=sub{die "\n\nYou hit control C\n\n"}; say "Press Enter" and <> while 1'

# Assign many signal handlers
perl -MData::Dumper -lE 'sub pr{my $d=Data::Dumper->new(\@_)->Purity(1); say $d->Dump} $SIG{INT}=sub{die"\nINT\n"}; $SIG{QUIT}=sub{die"\nQUIT\n"}; $SIG{TERM}=sub{die"\nTERM\n"};  $SIG{PIPE}=sub{die"\nPIPE\n"}; $SIG{ALRM}=sub{die"\nALRM\n"}; $SIG{HUP}...

# Assign many signal handlers
perl -MData::Dumper -le 'sub pr{print Data::Dumper->new(\@_)->Deparse(1)->Dump} for my $s(qw/INT QUIT TERM PIPE ALRM HUP CHLD __WARN__ __DIE__/){ $SIG{$s} = sub{die"\n$s\n"}} pr \%SIG; <> while 1'
perl -MData::Dumper -le 'sub pr{print Data::Dumper->new(\@_)->Deparse(1)->Dump} for my $s(keys %SIG){ $SIG{$s} = sub{print "\n$s\n"}} pr \%SIG; print $$; <> while 1'

# Alarm signal handler
perl -le 'for my $s(qw/INT QUIT TERM PIPE ALRM HUP CHLD/){ $SIG{$s} = sub{die"\n$s\n"}} alarm 2; <> while 1'
perl -le '$SIG{ALRM}=sub{die"\n\nEND OF TIME\n\n"}; alarm 1; <> while 1'

# Perl signal handling (eval,die,exit)
perl -E 'eval { exit 1 }; say $@; say "here"'         # Blank
perl -E 'eval { exit 0 }; say $@; say "here"'         # Same
perl -E 'eval { return 1 }; say $@; say "here"'       # Return early from an eval. ürints "here"
perl -E 'eval { die }; say $@; say "here"'            # caught die,                prints "here"
perl -E 'eval { exit 1 }; say $@; END {say "here"}'   # Run before final exit.     prints "here"
perl -E 'eval { die }; say $@; END {say "here"}'      # Same.
perl -E 'open FH, ">", "file"; say FH "123"; exit 1'  # File closed and contains "123"

# Perl signal handling (eval,die,exit)
# Avoid using $SIG{__DIE__}
https://www.perlmonks.org/?node_id=1173708
perl -E '$SIG{__DIE__} = sub { say "caught die!" }; die; say $@; say "here"'

# Perl signal handling (eval,die,exit)
# Catch exit command.
perl -E 'BEGIN{ *CORE::GLOBAL::exit = sub(;$){die "EXIT_OVERRIDE: @_\n"} } eval { exit 1 }; print "caught error: $@" if $@; say "here"; exit 0'

# Perl signal handling (eval,die,exit)
# exit overrite snippet. Plus capture all signals.
# exit overrite snippet. Plus capture all signals.
our $ExitOverride = 1;
BEGIN {
    *CORE::GLOBAL::exit = sub {
        die "EXIT_OVERRIDE:Caught: @_\n" if $ExitOverride;
        CORE::exit(@_);
    };
}
local %SIG = %SIG;
KEY:
for my $Key ( sort keys %SIG ) {
    next KEY if $Key eq 'CHLD';
    next KEY if $Key eq 'CLD';
    next KEY if $Key eq '__DIE__';
    next KEY if $Key eq '__WARN__';
    $SIG{$Key} = sub { die $Key };    ## no critic
}
#
# RUN CODE HERE
#
$ExitOverride = 0;

# Perl signal handling (eval,die,__DIE__)
# Capture STDOUT and STDERR.
# Catch die and throw to STDOUT.
perl -MApp::Pod -E '{ local *STDOUT; open STDOUT, ">", \$out or die $!; local *STDERR; open STDERR, ">>", \$err or die $!; print "print-out"; print STDERR "print-err"; local $SIG{__DIE__} = sub{ my $m = shift; chomp $m; print STDERR "<$m>" }; eval{di...
#
# Use $@ to capture eval error.
# Better than SIG{__DIE__} since sub calls may except an die
# to stop something, like Pod::Simple, which is used by Pod::LOL).
perl -Ilib -MApp::Pod -E '{ local *STDOUT; open STDOUT, ">", \$out or die $!; local *STDERR; open STDERR, ">>", \$err or die $!; print "print-out"; print STDERR "print-err"; eval{die "die\n"}; print STDERR "<$@>" if $@; print "print-out2" } say "\n[$...

# Redirect to terminal even when STDOUT and/STDERR are sent somewhere else.
perl -E 'open my $fh, ">", "/dev/tty" or die $!; close *STDOUT; say $fh "111"; say "HERE"; say $fh "123";'
111
123
pod e say

# Perl Signal Handling
# Another  interesting  signal  is  signal  number  0.
# This  doesn’t  actually  affect  the target  process,
# but  instead  checks  that  it’s  alive  and  hasn’t
# changed  its  UIDs. That  is,  it  checks  whether
# it’s  legal  to  send  a  signal,  without  actually
# sending  one. 
unless (kill 0 => $kid_pid) {     
  warn "something wicked happened to $kid_pid"; 
}


#############################################################
## Perl Symbol Table
#############################################################

# Remove a subroutine from the symbol table (perl)
# defined &abs_path will still return 1 since it still exists
# but we removed a reference to it.
delete $Cwd::{'abs_path'}

# Remove the contents of a subroutine (perl)
# defined &abs_path will return 0
# Still found in symbol table
undef $Cwd::{'abs_path'}

# Snippet to capture output in perl.
# Capture output.
my $output = "";
{
    local *STDOUT;
    local *STDERR;
    open STDOUT, ">",  \$output or die $!;
    open STDERR, ">>", \$output or die $!;
    eval { App::Pod->run };
    if ( $@ ) {
        $output = $@;
        chomp $output;
    }
}

# Backup and restore STDOUT in perl.
# Backup current STDOUT
open(my $backup_stdout, '>&', STDOUT) or die "Can't duplicate STDOUT: $!";
# Redirect STDOUT to a file
open(STDOUT, '>', 'output.txt') or die "Can't redirect STDOUT: $!";
# Write to the redirected STDOUT

cheats.txt  view on Meta::CPAN

perl -E '"abc" =~ /(?<a>.)(?<b>.)(?<c>.)/; say for sort keys %+'
a
b
c
perl -E '"abc" =~ /(?<v>.)(?<v>.)(?<v>.)/; say for $-{v}->@*'
a
b
c


#############################################################
## Perl Variables - %INC
#############################################################

# Find Perl library
perl -le 'print "$_ -> $INC{$_}" for keys %INC'


#############################################################
## Perl Variables - @INC, $ENV{PERL5LIB}
#############################################################

# Can use PERL5LIB to automatically file in @INC.

# Perl Variables - @INC, $ENV{PERL5LIB}
# Old versions of perl can SEGV when it is added
# an interator hook coderef.
#
# While in older versions of perl having a hook
# modify @INC was fraught with issues and could
# even result in segfaults or assert failures,
# as of 5.37.7 the logic has been made much more
# robust and the hook now has control over the
# loop iteration if it wishes to do so.


#############################################################
## Perl Variables - %ENV
#############################################################

# User %ENV and system calls (affect sub process) (Milton)
export ABC=outside
perl -le '$ENV{ABC}="inside"; system q(echo "$ABC")'
# prints inside

# Each sub process has a separate ENV list
perl -le 'system q(export ABC=456; echo "$ABC"); print "-$ENV{ABC}"; system q(echo "$ABC")'


#############################################################
## Perl Variables - %{^HOOK}
#############################################################

# Perl Variables - %{^HOOK}
As of 5.37.10,
prior to any other actions it performs,
require will check if ${^HOOK}{require__before}
contains a coderef, and if it does it will be
called with the filename form of the item being
loaded. The hook may modify $_[0] to load a
different filename, or it may throw a fatal
exception to cause the require to fail, which
will be treated as though the required code
itself had thrown an exception.
perl -E '
    use warnings;
    BEGIN{
        ${^HOOK}{require__before} = sub {
            say "here: @_";
            $_[0] =~ s/Scalar/List/;
        };
    }
    use Scalar::Util qw( reftype );
    my $v = [];
    say reftype $v
'
here: Scalar/Util.pm
here: strict.pm
here: warnings.pm
here: strict.pm
here: Exporter.pm
here: strict.pm
here: strict.pm
here: XSLoader.pm
here: strict.pm
here: strict.pm
Unquoted string "reftype" may clash with future reserved word at -e line 1.
Name "main::reftype" used only once: possible typo at -e line 1.
say() on unopened filehandle reftype at -e line 1.

# Perl Variables - %{^HOOK}
As of 5.37.10,
There is a similar hook that fires after require
completes, ${^HOOK}{require__after}, which will
be called after each require statement completes,
either via an exception or successfully. It will
be called with the filename of the most recently
executed require statement. It is executed in an
eval, and will not in any way affect execution.


#############################################################
## Perl Variables - $/ (IRS)
#############################################################

# Perl Variables - $/ (IRS)
# Commandline -0
-0    - null
-013  - octal new line
-0xd  - hex new line
-00   - paragraph mode
-0777 - slurp mode
#
# $/
undef - slurp mode
blank - paragraph mode
\256  - fixed byte mode


#############################################################
## Perl Variables - *STDOUT
#############################################################

# Redirect STDOUT to a variable in perl

cheats.txt  view on Meta::CPAN

#############################################################
## Vim Script/Coding Structures (Functions
#############################################################

# Comparison in conditional (Vim,equal)
:if 1 == 1 | echo "TRUE" | else | echo "FALSE" | endif
# TRUE

# Comparison in conditional (Vim,equal,strings)
:if "abc" == "abc" | echo "TRUE" | else | echo "FALSE" | endif
# TRUE
# Comparison in conditional (Vim,equal,strings)
:if "abc" == "def" | echo "TRUE" | else | echo "FALSE" | endif
# FALSE

# Comparison in conditional (Vim,equal,strings)
:if "10abc" == "10def" | echo "TRUE" | else | echo "FALSE" | endif
# FALSE

# Comparison in conditional (Vim,equal,strings)
# Like perl. Uses leading numbers
:echo "10abc" + "10def"
# 20

# Comparison in conditional (Vim,equal,strings)
# Case sensitive ?
:if "abc" == "Abc" | echo "TRUE" | else | echo "FALSE" | endif
# FALSE
:set ignorecase
:if "abc" == "Abc" | echo "TRUE" | else | echo "FALSE" | endif
# TRUE
# Always use safer form ==? ==#
# ==?    - always case insensitive
# ==#    - always case sensitive
:if "abc" ==? "Abc" | echo "TRUE" | else | echo "FALSE" | endif
# TRUE
:if "abc" ==# "Abc" | echo "TRUE" | else | echo "FALSE" | endif
# FALSE


#############################################################
## Vim Functions
#############################################################

# Create a function (Vim)
# Must start with a capital letter
:function Abc()
:  echo "ABC"
:endfunction

# Define a function to return a value (Vim)
:function Abc()
:  return "ABC"
:endfunction

# Call a function (Vim)
# () are required.
:call Abc()

# Return a value from a function (Vim)
# :call will throw away the return value
# Use your function as an expresion instead.
:echo Abc()

# Create function inline (Vim)
# Not really friendly view.
:execute "function A()\necho \"ABC\"\nendfunction"

# Silence function redefinition with "!" (Vim)
:function! ABC()
:  echo "ABC"
:endfunction

# Return a sorted list (Vim)
function Sorted(l)
   let new_list = deepcopy(a:l)
   call sort(new_list)
   return new_list
endfunction
:let list = [3,6,1,2]
:echo Sorted(list)

# Save function reference in a scalar variable (Vim)
:let My_func = function("Sorted")
:let list = [3,6,1,2]
:echo Sorted(list)

# Higher order functions (Vim,pass function as parameter/argument)
function! Mapped(f,l)
   let new_list = deepcopy(a:l)
   call map(new_list, string(a:f) . '(v:val)')
   return new_list
endfunction
"
function! Sorted(l)
   let new_list = deepcopy(a:l)
   call sort(new_list)
   return new_list
endfunction
"
:let list = [[3,1,2],[23,12,3]]
:echo Mapped(function("Sorted"),list)

# Inside a map(), 'v:val' is the current item item in the list (Vim,function)
# Like $_ in perl


#############################################################
## Vim Plugins
#############################################################

# Setup plugin manager in Vim
# Download plug.vim
# Save here: ~/.vim/autoload/plug.vim

# Using plugins in vimrc
# Install vim-plug.
sudo apt install nodejs
curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
    https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim



( run in 1.546 second using v1.01-cache-2.11-cpan-75ffa21a3d4 )