My name is Darek, I live in Poland. I'm working in IT. This page contains some info mainly about my works. I write scripts which solve some non-standard problems - sometimes trivial, sometimes complex. I write them fast, some of my scripts are simply working prototypes. That's where I'm good at. You can find my CV here: here

Javascript filter() function weirdness

24.01.2020 Works as expected:
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter((word, index) => [0,3].indexOf(index) !==-1);

console.log(result);
//Array ["spray", "exuberant"]
But ... If we put callback function body into {} braces (curly brackets) and if return is omitted (as if in previous example) we got [] !!!
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter((word, index) => { [0,3].indexOf(index) !==-1 });

console.log(result);
//Array []

Simple Bash and Python 2.7 scripts to handle Docker images and containers on basic CentOS box

07.01.2020 In my day-to-day work I use basic CentOS box as Docker host. I've written some scripts to make Docker basic operations easier. Because it's basic CentOS 7 shipped with Python 2.7 and Bash interpreter I decided to use them. The first script's aim (start.py) is to list existing images, select one of them, select parameters (stored in plaintext file docker-run-params.txt) to run with and then run the container. To check if docker run ... command succeeded or failed the script examines docker inspect ... command JSON output.
start.py:
#!/usr/bin/python
#v0.04

import subprocess, os, json
from datetime import datetime
"""
docker images --format '{{.Repository}}\t{{.ID}}\t{{.Tag}}'
"""
cmd = ["docker", "images", "--format",  "{{.Repository}}\t{{.Tag}}\t{{.ID}}\t{{.CreatedSince}}\t{{.Size}}"]
cmdOutput = subprocess.check_output(cmd)
lImages = []
lImages = cmdOutput.split("\n")

RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'

if (len(lImages)):
	for index in range(len(lImages)-1):
		lImages[index] = lImages[index].split("\t");
		print '%2i %-20s %-10s %-8s %-15s %10s' % (index + 1 , lImages[index][0] , lImages[index][1] , lImages[index][2], lImages[index][3], lImages[index][4]);
		#print lImages[index][0]

	msg = "choose 1-%i or q : " % (len(lImages) - 1)
	anwser = raw_input(msg)

	if (anwser == "q"):
		quit()
	else:
		#print lImages[int(anwser)][0]
		i = int(anwser) - 1
		now = datetime.now()
	        date_time = now.strftime("%m%d%Y-%H%M%S")

		file = open("docker-run-params.txt", "r")
		lines = file.readlines()
		lines = map(lambda item: item.rstrip(), lines)

		for index in range(len(lines)):
			print index + 1, lines[index]

		msg = "choose 1-%i or q : " % (len(lines))
		anwser = raw_input(msg)

	  	if (anwser == "q"):
	 		quit()
		else:
			i2 = int(anwser) - 1
		  	dockCmd = 'docker run %s' % (lines[i2].replace("<name>", "%s").replace("<repository>", "%s").replace("<tag>", "%s"))
			dockCmd = dockCmd % (date_time, lImages[i][0], lImages[i][1])
			print dockCmd

			os.system(dockCmd)
		  	"""
			subprocess.check_output(["docker", "inspect", "-f", "{{.State.Running}}", "12122019-102612"])
			"""
		 	# force to output JSON string
			cmdOutput = subprocess.check_output(["docker", "inspect", "-f", "{{json .State}}", "--type", "container", date_time])
			oJSON = json.loads(cmdOutput)
			if (oJSON['Running'] == False):
				print 'command:\n', dockCmd, RED, '\nfailed', NC
			else:
				print 'command:\n', dockCmd, GREEN, '\nsucceeded', NC
docker-run-params.txt:
--privileged -v /sys/fs/cgroup:/sys/fs/cgroup:ro -p 80:80 -d --name <name> <repository>:<tag> 
--privileged -v /sys/fs/cgroup:/sys/fs/cgroup:ro -p 445:445 -d --name <name> <repository>:<tag> 
-it -p 3000:3000 --name <name> <repository>:<tag> bash
To be continued ...

How to create docker image of CentOS 7 basic system in order to create customized docker images

24.10.2019 I have basic CentOS7 installation (+ docker) running. I found I can use mkimage-yum.sh script from Moby Project in order to create docker image of it. Its use is pretty straightforward:
# docker must be installed and running
$ systemctl start docker
# assume 'root' here and 0755 script rights
$ ./mkimage-yum.sh centos7-basic
# then we check if image is listed
$ docker images
# save image as .tar file (for future use)
$ docker save centos7-bare > centos7-bare.tar
Then you can run container using this image:
$ docker run [options] --name <some-container-name> <repository>:<tag>
Notice: We assign name to the container. Inside container you can install specific software, configure it. In my case I just needed Docker image that contains Sybase Anywhere 12 Client installed and configured. Then in order to create customized image you just need exit container and issue on host CentOS:
$ docker commit [options] --name <some-container-name> <repository>:<tag>
That will create new version of the image that contains all changes we made.

Reducing used disk space by removing some backups

14.10.2019 In my work we have two QNAP's machines. They are used as additional backup servers. They store database files in directories whose names are made up of date and hour/minutes of backup creation. Disk space of one of these servers was almost full. Both servers are accessible via ssh using 'admin' account. There is no Nodejs or Perl installed (by default) but Python 2.7 is. So my task was to reduce used disk space by deleting some of these directories. There are two files in each backup directory .log and .db. I wrote Python 2.7 script using standard modules (that come by default with Python). In short - that script (run with no command line arguments) search for case where at least two subsquent backups have the same size of .db file and allows you delete former backup directory. You can also do this for all such cases using "--all" command line argument or you can list and check if such cases exist using "--show" switch. Working (but still not fully tested, use at your own risk!!!, be careful!!!) version was ready after 3 days but I was doing other things too so I assume I spent 1.5 day on this. BTW - I haven't used Python for many years (8 or so)
#!/usr/local/bin/python
# ver: 0.6

import glob
import os
import sys
# 2018-10-18_23-00
files = glob.glob("*-*-*_*-*/*")

items = {}

for file in files:
    statinfo = os.stat(file)
    #print statinfo.st_size, file
    items[file] = statinfo.st_size

#print files


def SortByNumPart(key):
    parts = key.split("/")
    return [-int(parts[0].replace("-", "").replace("_", "")), parts[1]]


# list
itemsSorted = sorted(items, key=SortByNumPart)

logItemSorted = filter(lambda item: item.split(".")[-1] == "log", itemsSorted)
dbItemSorted = filter(lambda item: item.split(".")[-1] == "db", itemsSorted)
aDirs = map(lambda item: item.split("/")[0], logItemSorted)

# for sItem in logItemSorted:
#	print sItem, "\t", items[sItem]

aOutput = []
for index in range(len(aDirs)):
    sDate = logItemSorted[index].split("/")[0]
    if (len(aDirs) > index + 1):
        sDateNext = logItemSorted[index + 1].split("/")[0]
        if (sDate == dbItemSorted[index].split("/")[0]):
            aOutput.append([
                sDateNext,
                items[logItemSorted[index + 1]],
                items[dbItemSorted[index + 1]],
                sDate,
                items[logItemSorted[index]],
                items[dbItemSorted[index]],
                items[logItemSorted[index + 1]] - items[logItemSorted[index]],
                items[dbItemSorted[index + 1]] - items[dbItemSorted[index]]
            ])


def findLastZero(mylist, pos):
    ret = -1
    for index in range(len(mylist)):
        if (mylist[index][pos] == 0):
            ret = index
    return ret


if (len(sys.argv) == 1):
    sDirItem = None

    last = findLastZero(aOutput, 7)
    last = last + 1

    for row in aOutput[0:last]:
        print '%-15s %15i %15i %-15s %15i %15i %15i %15i' % (
            row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7])
        if (row[5] - row[2] == 0):
            sDirItem = row[0]

    if (sDirItem):
        print "rm -rf", sDirItem
        anwser = raw_input('run [Y|y]es/[N|n]o ? ').lower()

        if (anwser == "y"):
            os.system("rm -rf " + sDirItem)
        else:
            print "You didn't choose 'Y|y'"

elif (sys.argv[1] == '--all'):
    aDirItems = []
    for row in aOutput:
        if (row[5] - row[2] == 0):
            print '%-15s %15i %15i %-15s %15i %15i %15i %15i' % (
                row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7])
            aDirItems.append(row[0])

    if (len(aDirItems)):
        print "rm -rf", " ".join(aDirItems)
        anwser = raw_input('run [Y|y]es/[N|n]o ? ').lower()

        if (anwser == "y"):
            os.system("rm -rf " + " ".join(aDirItems))
        else:
            print "You didn't choose 'Y|y'"

elif (sys.argv[1] == '--show'):
    # list reversed, latest first
    for row in aOutput[::-1]:
        print '%-15s %15i %15i %-15s %15i %15i %15i %15i' % (
            row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7])