Category Archives for computers

POST request turns into GET request

I was firing login request to my API but I could not get it to return the correct response.

Upon investigation, it turns out that the API received a GET request while I issued a POST request with Postman.

The issue? I was sending the POST request to http while the API was listening on https!

It turns out that the request was forwarded to the https address as a GET request…

Solution: send requests to the https address

Docker on Windows: /usr/bin/env: bash\r No such file or directory

Getting the following error when you want to start your Docker container on Windows: /usr/bin/env: bash\r : No such file or directory

[edit]

I discovered that another fix is to do dos2unix <file>

dos2unix <file with the issues>

Try that if you’re on Windows or working with others who work on Windows.

[/edit]

I found several topics with several fixes. But what fixed it for me was:

Solution: Setting the line-endings correctly

  • In my editor: \n
  • In git: git config --global core.autocrlf false

I chose the \n line ending as this is stated in PSR-12: 2.2 Files:
All PHP files MUST use the Unix LF (linefeed) line ending only.

I use PHPStorm and had to go to
Settings > Editor > Code Style > tab General > Unix and macOS (\n)

NOTE: you may have to do the following to fix files with the wrong line-endings:

  • remove the built Docker image on Windows: first list docker images and then delete: docker rmi <imagename>
  • fix the line-ending of the file. You might do that by removing the newline and adding a new one. Don’t forget to save, commit and push

Add mobx to your React project

Mobx helps you manage the state.

I set up mobx to be used as an import to your (functional) components. I do this, rather than using createContext() because the latter one only allows you to use it inside components, not functions.

To set up mobx you’ll need to:

  1. install mobx
  2. create store
  3. configure store and components

In this example, I make use of the function autoStore() in the constructor of the store to save the state to localStorage whenever there is a change to the state.
This makes that state is saved across page-refreshes.

install mobx

Install with:

yarn add mobx mobx-react

create store

Create your store by creating file src/stores/uiStore.tsx.

This will be one of the stores you can use. You can create as many stores as you want.

// file src/stores/uiStore.tsx
import {makeAutoObservable} from "mobx";

const uiStore = () => makeAutoObservable({
    showLocations: false as boolean,
    toggleShowLocations(){
        this.showLocations = ! this.showLocations
    },
})

export default uiStore

Next, we add this store to the context. This makes that we can access all stores via the useStore context.

// file ./src/stores/index.tsx
import {createContext, useContext} from "react";
import uiStore from "./uiStore";

const store = {
    ui: uiStore(),
}

export const StoreContext = createContext(store)

export const useStore = () => {
    return useContext<typeof store>(StoreContext)
}

export default store

In your App.tsx, add the StoreContext so every child component can make use of it.

// file ./src/App.tsx
...
import store, {StoreContext} from "../stores";
...

const MyApp = () => {
    ...

    return (
      <StoreContext.Provider value={store}>
            <Header />
            <Switch>
                  ...
            </Switch>
      </StoreContext.Provider>
    )
}

File ./src/libs/autoStore.js takes care of storing the state in localStorage.

// file ./src/libs/autoStore.tsx
import { toJS, autorun, set } from 'mobx'

export default function (_this: any, storeName='store') {
    let firstRun = true

    // will run on change
    autorun(() => {
        // on load check if there's an existing store on
        // localStorage and extend the store
        if (firstRun) {
            const existingStore = window.localStorage.getItem(storeName)

            if (existingStore) {
                set(_this, JSON.parse(existingStore))
            }
        }

        // from then on serialize and save to localStorage
        const serializedThis = toJS(_this)
        window.localStorage.setItem(
            storeName,
            JSON.stringify(serializedThis)
        )
    })

    firstRun = false
}

Use the store: configure store and components

Configure your components by wrapping them with the observer() function of mobx.

By doing this, mobx knows whenever something changes that concerns the state.

// file ./src/components/SayHello.js

import React, { Component } from 'react'
import { observer } from 'mobx-react-lite'
import {useStore} from "../../stores";

const SayHello = () => {
   const {ui} = useStore()

   return <div>{ui.showLocations && 'Hi locations!'}</div>
}

export default observer(SayHello)

Resources

Take a look at these pages. They provide useful information about working with mobx.

Caprover doesn’t set MySQL user or database

The problem: one-click app MySQL won’t create database or user

In caprover, formerly captainduckduck, I had the issue that the database and a user were not created by setting environment variables MYSQL_USER and MYSQL_DATABASE.

While building, this message was displayed by Docker:

[Warning] One or more build-args [MYSQL_USER, MYSQL_DATABASE] were not consumed

So appearently, Caprover does not support setting the environment variables for (only?) MySQL anymore.

Selecting MySQL from the oneclick-apps gives you the following options.
Note the absence of setting extra environment variables.

adding a MySQL one-click-app in Caprover

You can only set the root password.

When you start this new app, only the root password is set. If you now set the environment variables, MySQL will not create the database or user. It does this only on first startup, after creating the one-click-app for MySQL.

Solution: supply Dockerfile with the environment variables set

My workaround? Don’t use a one-click app and supply a Dockerfile directly inside Caprover instead.

This is what I used:

  1. Create a new app (and select ‘has persistent data‘)
  2. Open the newly created app by clicking on its name in the Apps overview
  3. Click tab ‘Deployment
  4. Scroll down to ‘Method 4: Deploy plain Dockerfile
  5. Insert and edit the following content and click on ‘Deploy Now
ENV MYSQL_ROOT_PASSWORD=S3cretR00t
ENV MYSQL_DATABASE=dbname_for_app
ENV MYSQL_USER=app_user
ENV MYSQL_PASSWORD=An0therS3cret
adding Dockerfile contents directly into your app

When you deploy your new database app now, the database and the user will be created.

Help your future self: set environment variables after the fact

TIP: after this, you won’t see the Dockerfile contents anymore. So in the future it might be unclear what values were set.
In order to overcome this, set the environment variables as well over at App Configs > Environmental variables:

MYSQL_ROOT_PASSWORD=S3cretR00t
MYSQL_DATABASE=dbname_for_app
MYSQL_USER=app_user
MYSQL_PASSWORD=An0therS3cret
add the environment variables in ‘bulk mode’

That’s it! Now let’s hope we’ll be able to set environment variables in the one-click setup some day soon again.

Bash: use colored text in script

I often use these handy helperfunction to write colored text in my scripts.

# Bash text-colors
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color

function echoRed() {
  TEXT=$1
  printf "${RED}${TEXT}${NC}\n"
}

function echoGreen() {
  TEXT=$1
  printf "${GREEN}${TEXT}${NC}\n"
}

echoGreen "This text is green"
echoRed "This text is red"
echo "This is regular text"

XPATH: search element by text

When I write selenium/kantu end-to-end test I often need to use xpath to find certain elements.
And while it’s definitely not the fastest, searching elements by the text in it, is easy and fast to use. It’s also more descriptive to an untrained eye.

I often refer to this post on StackOverflow which has it written down quite neatly: https://stackoverflow.com/a/2994336

It basically comes down to this:

Literal match (= must match exactly and completely):

//*[text()='match']
//button[text()='Save']

This matches: elements containing (just) the text ‘match’ and a button with (just) the text ‘Save’

Do you need to strip whitespace from texts in elements before you do the matching, then use this:

//*/text()[normalize-space(.)='match']/parent::*

Partly matching:

If it’s ok to be not so strict, use this more loosely matching:

//*[contains(text(),'match')]

This matches texts like: ‘this match comes up‘ and ‘matches this’

If your text must match with words beginning with the text or lines starting or ending with that text, use this xpath 2.0 expression:

//*[matches(text(),'(^|\W)match($|\W)','i')]

Search element with specific class

//*[contains(@class, 'Test')]

Get parent element

//*[contains(@class, 'Test')]/parent::*
or
//*[contains(@class, 'Test')]/..

Multiple conditions

NOTE: that you MUST use single quotes and the word ‘and’ MUST be lowercase.

//*[contains(@class, 'Test') and contains(text(), 'match this text')]

//button[@id='add-user' and contains(@class, 'active')]

PRO-tip: use the inspector to test your xpath.

open the inspector and search (<C-f> or <Command+F>)

Docker opschonen: vrije ruimte terugkrijgen

Als je Docker een tijdje gebruikt hebt, dan kan het zeker lonen om de boel eens op te schonen. Door items te verwijderen die je niet meer nodig hebt kun je een hoop ruimte vrijmaken.

TL;DR

Voer deze commando’s uit om alles op te ruimen

docker system prune
docker images --no-trunc | grep '<none>' \
    | awk '{ print $3 }' \
    | xargs docker rmi
docker ps --filter status=dead --filter status=exited -aq \
  | xargs docker rm -v
docker volume ls -qf dangling=true | xargs docker volume rm
Continue reading

Watch files and execute command upon change

Find yourself executing the same command over and over again after applying changes to certain files? Pywatch will be you best friend!

Meet pywatch: a cool little app that watches directories and files. Whenever it finds a file that changed, it executes the command you provided.

TL;DR

As an example; I use this to build a Docker image whenever I save a change to my Dockerfile.

pywatch "docker build . -t pauledenburg/behat" Dockerfile

Or execute tests whenever I make a change to one of the sourcefiles.

commandToExecute='docker exec -i hangman_app_1 behat -c tests/behat/behat.yml'
find ./tests -name "*.php" -o -name "*.feature" \
  | xargs pywatch "$commandToExecute"

This keeps an eye on all *.php and *.feature files under ./tests.

When one of these files changes, it executes $commandToExecute which resolves to executing behat in a Docker container.

Install

Download the pywatch app from github: https://github.com/cmheisel/pywatch.

Then unzip and install with python.

unzip pywatch-master.zip
cd pywatch-master
sudo python setup.py install

Advanced usage

Nice one: run tests when files change and create a Mac notifier whenever the tests fail.

This way you can keep the tests running in the background and you’ll be notified whenever a test failed.

find src tests -name "*.php" -o -name "*.feature" \
  | xargs pywatch "./dev test phpunit" \
  | grep "([0-9]* failed)" \
  | sed -e 's/.*(\([0-9]* failed\)).*/\1/' \
  | while read failure; 
    do 
      terminal-notifier -message "Test output: $failure" -title "Tests Failed!"
    done