all_notes

Spring @Value annotated methods

Spring supports @Value methods on:

  • class instance variables (i.e. they are not static)
  • on setter methods - which leads to a workaround for the above static limitation, for example:
static String someVariable

@Value("{someVar}")
public void setSomeVariable(String someVar){
    someVariable = someVar;
}

Java_and_Spring
0
Bash: easy health check for TCP connections

Useful for "living off the land" techniques or in scripts:

timeout 1 bash -c "cat /dev/null > /dev/tcp/google.com/80"
echo $? # 0 = OK

TLDR: run the command "cat /dev/null > /dev/tcp/google.com/80" which uses linux's TCP device files and wait for 1 second. If the TCP connection is successful, exit code will be 0

Uwrapping the above command from the end:

  • /dev/tcp/google.com/80 : we're using linux's inbuilt TCP/IP dev files
  • cat /dev/null > /dev/tcp/google.com/80 : sending "null" to this endpoint (google.com, port 80)
  • Sending "null" will obviously not return any valid data, but it will attempt to open a TCP connection to our target. In order not to wait around forever, we use the timeout command, and wait for one second for our cat command to complete
  • Because we use a redirect in the bash command we feed into timeout, it's easier to wrap the command with inverted commas (to avoid redirecting the output of "timeout" itself by mistake), and feed it into bash -c which accepts string commands and feeds them to bash
  • echo $? outputs the previous command's exit code. In this case, 0 will mean TCP connection was successful, and otherwise a non-zero exit code is returned

Linux
InfoSec
0
Python: co-routines in multi-threading/processing

Asyncio contains the event_loop.run_in_executor function which allows you to run co-routines in a separate executor - this being a Thread or Processor pool (via the concurrent.futures module):

def blocking_task(i):
   print(i) #or some other useful task...

async def run_blocking_tasks(executor):
    loop = asyncio.get_event_loop()
    blocking_tasks = [
        loop.run_in_executor(executor, blocking_task, i)
        for i in range(6)
    ]

    completed, pending = await asyncio.wait(blocking_tasks)
    results = [t.result() for t in completed]
    return results

event_loop = asyncio.get_event_loop()
try:
    event_loop.run_until_complete(
        run_blocking_tasks(executor)
    )
finally:
    event_loop.close()

Important: note that the last argument to run_in_executor is *args, i.e. the arguments to pass to the blocking task. Passing the argument directly (blocking_task(i)) will not work as expected

Python
0
Python: custom sorting

Python3 allows us to sort iterables using the sorted function. It also allows us to define a "key function". The key function accepts a single parameter - an item from the iterable. It returns an integer, the lower the integer, the higher up in the sorted list (i.e. an item which returns 1 will appear before an item which returns 2)

Let's define an iterable of dicts:

listOfDicts = [{
     'level': 'high',
     'id' : 3
 },
 {
     'level': 'low',
     'id' : 2
 },
 {
     'level': 'low',
     'id' : 1
 },
 {
     'level': 'medium',
     'id' : 4
}]

We'd like to have dicts whose level attribute is high to appear first in the list, followed by medium, and last by low. Let's define a suitable key function to do this:

def custom_sort_function(obj):
     if (obj['level'] == 'high'):
             return 1
     if (obj['level'] == 'medium'):
             return 2
     if (obj['level'] == 'low'):
             return 3
     return 4

Last, we apply the above function to our iterable using sorted. P.S. note how we use a lambda to feed each entry into the custom_sort_function - this is not necessary - you can just provide the function name

sorted(listOfDicts, key=lambda x : custom_sort_function(x))
# - OR -
sorted(listOfDicts, key=custom_sort_function)

Which returns the sorted list as expected:

[{'level': 'high', 'id': 3}, {'level': 'medium', 'id': 4}, {'level': 'low', 'id': 2}, {'level': 'low', 'id': 1}]

Python
0
Kotlin: Top two null-safety tricks

  • The elvis operator (?:) allows you to assign a "default" value if the variable to the left of the elvis operator is null

  • The notation someVariable?.let{ } allows you to take an action (which is defined within "let") only if someVariable is non-null

fun main() {
    // the elvis operator
    val test = null    
    val test2 = test ?: "it was null"  
    println(test2)
    
    // taking action only if variable is non-null
    // using ?.let
    val isNull = null
    isNull?.let{
        println("Inside let with null - will not be printed")
    }
    
    val isNotNull = 1
    isNotNull?.let{
        println("Inside let with non-null value of '$it' - will be printed")
    }
    
}

Output:

it was null
Inside let with non-null value of '1' - will be printed

Kotlin
0
Python dictionary (list) comprehensions

It's possible to generate a dictionary using comprehensions:

t = ["1", "234", "45"]
a = { keyName: len(keyName) for keyName in t }
print(a)
# prints: {'1': 1, '234': 3, '45': 2}

Python
0
Functional javascript: find unique elements in an array

Using only functional-style array methods to get the unique values in an array:

const sampleArray = [1, 2, 1, 3, 4]; // note "1" is repeated
const uniqueArray = sampleArray.filter( (value, idx, arr) => arr.indexOf(value) === idx );
console.log(uniqueArray);
// expected output is [1, 2, 3, 4]

This JS snippet takes advantage of two things:

  • The "filter" function actually takes three arguments which in addition to the usual "value" include the index and the original array which is being filtered
  • The array "indexOf" method by default returns only the first occurrence of whatever you pass to it

JavaScript
0
From Executor to CompletableFuture to Webflux

  • Executor (plain threading): allows you to define multiple threads (a pool of threads) which run atomic units of work in parallel. Depending on resources, max number of threads is limited. If on thread is blocked, it will wait until it can continue. (i.e. we have parallelism but no asynchronicity)

  • CompleteableFuture: allows the same as above, however now if a thread is blocked it can switch to another task while waiting for the original work to become unblocked. (i.e. now we have parallelism and asynchronicity)

  • Webflux: allows the same as the above, but where CompleteableFuture is eagerly executed, webflux is designed to be lazily executed (i.e. executed only when required - on subsciption). This allows the design to implement backpressure and control upstream workloads

Java_and_Spring
0
Python: Using "map" to update a list of dictionary

old_list = [{
   'fieldToUpdate': 'oldValue'
}]

new_list = list( map( lambda entry: entry.update({'fieldToUpdate': 'newValue'}) or entry, old_list) )

# new_list is now: [{'fieldToUpdate': 'newValue'}]

The above code snippet makes use of the fact that the "update" method of a standard python dict returns "None" - hence you can see the "or" being used to returned the newly updated entry

Python
0
Object to Array conversion

image

JavaScript
0
JSON.stringify() custom serialization

JSON.stringify() accepts a second parameter called "the replacer parameter". This parameter can be:

  • An array: the values in the function represent which keys of the object should be stringifyed into JSON. Anything not in the array is left out of the JSON string.

  • A function: the function accepts 2 parameters - key and value. The return value of this function is what will be inserted into the JSON object for the given key. Returning undefined omits the key from the JSON object. This allows you to provide custom logic when stringifying objects to JSON

JavaScript
0
JS Dynamic module importing

image

JavaScript
0
Create Kotlin Singletons using delegated properties

A typical java-like singleton would look like this in Kotlin:

class Singleton private constructor() {

     private object SingletonHolder {
            val INSTANCE = Singleton()
     }

    companion object {
            val instance : Singleton by lazy {
                        SingletonHolder.INSTANCE
            }
    }

}

The above code:

  • marks the constructor as private so you cannot create a new "Singleton" instance directly
  • contains a private object which can access the private constructor and so holds an instance of Singleton()
  • contains a companion object to return the instance

The important note here is the "by lazy" delegate property. by lazy is thread safe and hence avoids the double check code we normally use in Java to create a singleton. In addition, the companion object is itself a singleton, so we can shorten the above to:

class Singleton private constructor() {

    companion object {
            val instance : Singleton by lazy {
                        Singleton()
            }
    }

}

We simply got rid of the private SingletonHolder object, Furthermore, Kotlin shorthands all this to a single line:

object Singleton

Kotlin
0
JS Function closures for persistent memory

Javascript functions can return other functions, and the inner function has access to the scope of the outer function, making it useful to store variables persistently between function calls, for example:

var checkCookie = function() {
    var lastCookie = document.cookie; // 'static' memory between function calls
    return function() {
        var currentCookie = document.cookie;

        if (currentCookie != lastCookie) {
            // something useful like parse cookie, run a callback fn, etc.
            lastCookie = currentCookie; // store latest cookie
        }
    };
}();
window.setInterval(checkCookie, 100); // run every 100 ms

JavaScript
0
JS Destructuring Tricks

// example object:
let demo = {one: 1, two: 2}

// pick subset of keys
let {one} = demo

// rename variables
let {one: anotherOne} = demo
// "one" renamed to "anotherOne"

// provide default values
let {three = 3, one} = demo
// since "three" doesn't exist in demo, it's given the default value of "3"

// gather the rest
let {one, ...rest} = demo
//"rest" will contain anything from "demo" which is not "one"

JavaScript
0