Homelab, Linux, JS & ABAP (~˘▾˘)~
 

[ABAP] Report Template

*&---------------------------------------------------------------------*
*& Report Z_REPORT
*&---------------------------------------------------------------------*
*&
*&---------------------------------------------------------------------*
REPORT Z_REPORT.

*-----------------------------------------------------------------------
* SELEKTIONSBILD
*-----------------------------------------------------------------------

*-----------------------------------------------------------------------
* Zeitpunkt INITIALIZATION.
*-----------------------------------------------------------------------
INITIALIZATION.

*----------------------------------------------------------------------
* Zeitpunkt AT SELECTION-SCREEN
*----------------------------------------------------------------------
AT SELECTION-SCREEN OUTPUT. "PBO
  
*-----------------------------------------------------------------------
* Zeitpunkt START-OF-SELECTION.
*-----------------------------------------------------------------------
START-OF-SELECTION.
    
*----------------------------------------------------------------------
* Zeitpunkt END-OF-SELECTION
*----------------------------------------------------------------------
END-OF-SELECTION.

[VSC] Extensions

Open-source registry for VS Code extensions: https://open-vsx.org/

Coden

https://marketplace.visualstudio.com/items?itemName=CoenraadS.bracket-pair-colorizer-2
https://marketplace.visualstudio.com/items?itemName=vscode-icons-team.vscode-icons
https://marketplace.visualstudio.com/items?itemName=mechatroner.rainbow-csv

Git

https://marketplace.visualstudio.com/items?itemName=eamodio.gitlens
https://marketplace.visualstudio.com/items?itemName=mhutchie.git-graph

Markdown

https://marketplace.visualstudio.com/items?itemName=yzhang.markdown-all-in-one
https://marketplace.visualstudio.com/items?itemName=DavidAnson.vscode-markdownlint
https://marketplace.visualstudio.com/items?itemName=ban.spellright

Docker

https://marketplace.visualstudio.com/items?itemName=formulahendry.docker-explorer

WSL

https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-wsl

[nodejs] MongoDB and Mongoose Challenges

These are my notes while doing the course APIs and Microservices on https://www.freecodecamp.org. I highly recommend it if you prefer to try things directly rather than watching videos.


MongoDB is a database that stores data records (documents) for use by an application. Mongo is a non-relational, “NoSQL” database. This means Mongo stores all associated data within one record, instead of storing it across many preset tables as in a SQL database.
Mongo’s use of JSON as its document storage structure makes it a logical choice when learning backend JavaScript. Accessing documents and their properties is like accessing objects in JavaScript.

Mongoose.js is an npm module for Node.js that allows you to write objects for Mongo as you would in JavaScript.

MongoDB Atlas is a MongoDB Database-as-a-Service platform.


Install and Set Up Mongoose

Add mongodb and mongoose to the project’s package.json.

    "dependencies": {
        "body-parser": "^1.15.2",
        "dotenv": "^8.2.0",
        "express": "^4.12.4",
        "mongodb": "^3.6.4",
        "mongoose": "^5.11.15"
    },

Store your MongoDB Atlas database URI in a private .env file as MONGO_URI. Replace user and password.

MONGO_URI=mongodb+srv://<User>:<Password>@cluster0.xvsqx.mongodb.net/<dbname>?retryWrites=true&w=majority

Connect to the database using the following syntax:

const mongoose = require('mongoose');
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });

Create a Model

Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.

const { Schema } = mongoose;

const personSchema = new Schema({
  name: { type: String, required: true },
  age: Number,
  favoriteFoods: [String]
});

const Person = mongoose.model("Person", personSchema);

Create and Save a Record of a Model

The done() function is a callback that tells us that we can proceed after completing an asynchronous operation such as inserting, searching, updating, or deleting. It’s following the Node convention, and should be called as done(null, data) on success, or done(err) on error.

const createAndSavePerson = (done) => {

  let max = new Person({name: "Max", age: 31, favoriteFoods: ["Pasta"]});

  max.save((err, data) => {
    if (err) return console.error(err);
    done(null, data)
  });

};

Create Many Records with model.create()

var arrayOfPeople = [
    {name: "Max", age: 31, favoriteFoods: ["Pasta"]},
    {name: "Toni", age: 21, favoriteFoods: ["Pizza"]},
    {name: "Paul", age: 34, favoriteFoods: ["Bolo", "Penne"]}
    ];

const createManyPeople = (arrayOfPeople, done) => {
  Person.create(arrayOfPeople, (err, people) => {
    if (err) return console.error(err);
    done(null, people);
  });
};

Use model.find() to Search Your Database

Model.find() accepts a query document (a JSON object) as the first argument, then a callback. It returns an array of matches.

const findPeopleByName = (personName, done) => {
  Person.find({name: personName}, (err, personFound) => {
    if (err) return console.error(err);
    done(null, personFound);
  })
};

Use model.findOne() to Return a Single Matching Document from Your Database

Model.findOne() behaves like Model.find(), but it returns only one document (not an array), even if there are multiple items.

const findOneByFood = (food, done) => {
  Person.findOne({favoriteFoods: food}, (err, personFound) => {
    if (err) return console.error(err);
    done(null, personFound);
  })
};

Use model.findById() to Search Your Database By _id

When saving a document, MongoDB automatically adds the field _id, and set it to a unique alphanumeric key.

const findPersonById = (personId, done) => {
  Person.findById({_id: personId}, (err, personFound) => {
    if (err) return console.error(err);
    done(null, personFound);
  })
};

Perform Classic Updates by Running Find, Edit, then Save

const findEditThenSave = (personId, done) => {
  const foodToAdd = 'hamburger';

  Person.findById(personId, (err, person) => {
    if(err) return console.log(err); 
  
    person.favoriteFoods.push(foodToAdd);
    person.save((err, updatedPerson) => {
      if(err) return console.log(err);
      done(null, updatedPerson)
    })
  })
};

Perform New Updates on a Document Using model.findOneAndUpdate()

Use the function parameter personName as the search key. Set the person’s age to 20.
Note: You should return the updated document. To do that, you need to pass the options document { new: true } as the 3rd argument to findOneAndUpdate(). By default, these methods return the unmodified object.

const findAndUpdate = (personName, done) => {
  const ageToSet = 20;

  Person.findOneAndUpdate({name: personName}, {age: ageToSet}, { new: true }, (err, updatedDoc) => {
    if (err) return console.error(err);
    done(null, updatedDoc)
  })
};

Delete One Document Using model.findByIdAndRemove()

const removeById = (personId, done) => {

  Person.findByIdAndRemove(personId, (err, personDeleted) => {
    if (err) return console.error(err);
    done(null, personDeleted)
  })
};

Delete Many Documents with model.remove()

const removeManyPeople = (done) => {
  const nameToRemove = "Mary";

  Person.remove({name: nameToRemove}, (err, personsDeleted) => {
    if (err) return console.error(err);
    done(null, personsDeleted)
  })
};

Chain Search Query Helpers to Narrow Search Results

const queryChain = (done) => {
  const foodToSearch = "burrito";

  Person.find({favoriteFoods: foodToSearch})
  .sort({name: 1}) //sort bei name
  .limit(2) //only 2 results
  .select({age: 0})  //hide age
  .exec((err, twoPersonFound) => {
    if (err) return console.error(err);
    done(null, twoPersonFound)
  })
};

[nodejs] Basic Node and Express

These are my notes while doing the course APIs and Microservices on https://www.freecodecamp.org. I highly recommend it if you prefer to try things directly rather than watching videos.


Node.js is a JavaScript runtime that allows developers to write backend (server-side) programs in JavaScript. Node.js comes with a handful of built-in modules (small, independent programs) that help facilitate this purpose. Some of the core modules include:

  • HTTP: a module that acts as a server
  • File System: a module that reads and modifies files
  • Path: a module for working with directory and file paths
  • Assertion Testing: a module that checks code against prescribed constraints

Express (not included by default) runs between the server created by Node.js and the frontend pages of a web application. Also handles the app’s routing.

https://github.com/freeCodeCamp/boilerplate-express/


Start a Working Express Server

Let’s serve our first string! In Express, routes takes the following structure: app.METHOD(PATH, HANDLER). METHOD is an http method in lowercase. PATH is a relative path on the server. HANDLER is a function that Express calls when the route is matched.

app.get("/", (req, res) => {
  res.send("Hello Express");
});

Serve an HTML File

You can respond to requests with a file using the res.sendFile(path) method. This method needs an absolute file path. Use the Node global variable __dirname to calculate the path.
Send the /views/index.html file as a response to GET requests to the / path.

let absolutePath = __dirname + "/views/index.html";

app.get("/", (req, res) => {
  res.sendFile(absolutePath);
});

Serve Static Assets

Using express middleware to serve static files (stylesheets, scripts, images): app.use(path, middlewareFunction)

let staticFilesPath = __dirname + "/public";

app.use("/", express.static(staticFilesPath));

Serve JSON on a Specific Route

A REST (REpresentational State Transfer) API allows data exchange in a simple way, without the need for clients to know any detail about the server.

let dataJson = {"message": "Hello json"};

app.get("/json", (req, res) => {
  res.json(dataJson);
});

Use the .env File

The .env file is a hidden shell file that is used to pass environment variables to your application. Accessible from the app as process.env.VAR_NAME. Add variables to .env with this syntax: VAR_NAME=value

let dataJson = {"message": "Hello json"};

app.get("/json", (req, res) => {
 if (process.env.MESSAGE_STYLE === "uppercase") {
   dataJson.message = dataJson.message.toUpperCase();
 };

 res.json(dataJson);
});

Implement a Root-Level Request Logger Middleware

For every request, it should log to the console a string taking the following format: method path - ip. An example would look like this: GET /json - ::ffff:127.0.0.1.

app.use(function middleware(req, res, next) {
  console.log(req.method + " " + req.path + " - " + req.ip);
  next();
});

Chain Middleware to Create a Time Server

app.get('/now', 
(req, res, next) => {
  req.time = new Date().toString();
  next();
},  
(req, res) => {
  res.json({time: req.time})
});

Get Route Parameter Input from the Client

route_path: ‘/:word/echo’
actual_request_URL: ‘/myString/echo’
req.params: {word: ‘myString’}

app.get("/:word/echo", (req, res) => {
  res.json({"echo": req.params.word});
});

Get Query Parameter Input from the Client

route_path: ‘/name’
actual_request_URL: ‘/name?first=firstname&last=lastname’
req.query: {first: ‘firstname’, last: ‘lastname’}

app.get("/name", (req, res) => {
  res.json({name: `${req.query.first} ${req.query.last}`})
});

Use body-parser to Parse POST Requests

POST is the default method used to send client data with HTML forms. In REST convention, POST is used to send data to create new items in the database (a new user, or a new blog post).
In these kind of requests, the data doesn’t appear in the URL, it is hidden in the request body. The body is a part of the HTTP request, also called the payload.
Add "body-parser": "^1.15.2", in your package.json as dependencie to parse the body data.

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: false}));

Get Data from POST Requests

Mount a POST handler at the path /name.

app.post("/name", function(req, res) {
  res.json({name: `${req.body.first} ${req.body.last}`})
});

[nodejs] Managing Packages with NPM

These are my notes while doing the course APIs and Microservices on https://www.freecodecamp.org. I highly recommend it if you prefer to try things directly rather than watching videos.


The Node Package Manager (npm) is a command-line tool to share and control modules (or packages) of JavaScript code written for use with Node.js.

When starting a new project, npm generates a package.json file. This file lists the package dependencies for your project. Since npm packages are regularly updated, the package.json file allows you to set specific version numbers for each dependency. This ensures that updates to a package don’t break your project.

npm saves packages in a folder named node_modules. These packages can be installed in two ways:

  1. globally in a root node_modules folder, accessible by all projects.
  2. locally within a project’s own node_modules folder, accessible only to that project.

The package.json file is the center of any Node.js project or npm package. It stores information about your project, similar to how the <head> section of an HTML document describes the content of a webpage. It consists of a single JSON object where information is stored in key-value pairs.

https://github.com/freeCodeCamp/boilerplate-npm/

{
  "name": "fcc-learn-npm-package-json", // your project name
  "author": "Max Mustermann",
  "description": "A project that does something awesome",
  "keywords": [ "descriptive", "related", "words", "freecodecamp" ],
  "license": "MIT", // inform users of what they are allowed to do with your project
  "version": "1.2.0", // describes the current version of your project
  "dependencies": {
    "package-name": "MAJOR.MINOR.PATCH", // Semantic Versioning
    "express": "^4.14.0", 
    "moment": "~2.10.2" // handy library for working with time and dates.
  }
}

PATCHes are bug fixes and MINORs add new features but neither of them break what worked before. Finally, MAJORs add changes that won’t work with earlier versions. Find a more detailed explanation here.

To allow an npm dependency to update to the latest PATCH version, you can prefix the dependency’s version with the tilde (~) character.
The caret (^) will allow both MINOR updates and PATCHes.

[macOS] Boop

“Boop is a simple editor that allows you to execute scripts on the buffer. The idea is that you don’t have to paste potentially secret information into shady websites to do some simple transforms, like format json and decoding query strings.”

https://boop.okat.best/

There is also a port for Linux and Windows: https://github.com/zoeyfyi/Boop-GTK

sudo install boop-gtk.linux.amd64 /usr/local/bin/boop-gtk

Run from terminal with boop-gtk

[Linux Mint] Install PyWal on Linux Mint 20.1 Cinnamon

“Pywal is a tool that generates a color palette from the dominant colors in an image. It then applies the colors system-wide and on-the-fly in all of your favorite programs.”

https://github.com/dylanaraps/pywal/wiki/Installation

pip3 install pywal

I’m using Variety to change my wallpaper every day automatically. To always get the right colors in my terminal I added some lines in my .zshrc that will always grab the current wallpaper and pass it to PyWal. I’m sure a bash pro would do this in just one line… 🙂

#---PyWal---#
# load previous theme
(cat ~/.cache/wal/sequences &)
# get picture path
picturepath=$(gsettings get org.gnome.desktop.background picture-uri) 
# remove prefix & suffix
prefix="'file://" 
suffix="'"
picturepath=${picturepath#"$prefix"} 
picturepath=${picturepath%"$suffix"}
# set colors
wal -n -q -i "$picturepath"
#---PyWal End---#

There are many plugins/tools you can combine with PyWal:

https://github.com/frewacom/pywalfox

https://github.com/khanhas/Spicetify

https://github.com/themix-project/oomox