Tag: ai
Posts
A first encounter with ChatGPT
The arrival of DALL-E 2, Stable Diffusion, and GPT-3 has opened up a new world for developers, data scientists, and other tech adepts. These powerful AI models are capable of generating images, text, and other data in a wide range of styles and formats, and they offer exciting new possibilities for a variety of applications.
One of the most exciting developments in this field is ChatGPT, an AI model that is trained to generate conversational text in a natural and engaging way.
Tag: alert-rule
Posts
Update Azure Alert Rule Condition Query
For a lot of people probably a piece of cake, but I had to look a while before I could find it.
In Azure Portal, go to Alerts.
Go to Manage alert rules.
App names are hidden because of privacy reasons
Go to the application for which you want to edit the query.
Click on the condition whose query needs to be edited.
Tag: angular
Posts
Host a static Angular build in an Azure App Service
Building an Angular app usually results in a bunch of files, mainly consisting of Javascript files, CSS files, and an index.html.
An Azure App Service normally wants to host an application using a startup command for a specific stack (PHP, Node, Python, etc.).
Technically, you could run your Angular app as a Node app. In that case you would run npm run start or ng serve as the startup command.
Posts
Log errors to Azure Application Insights from an Angular app
As there is no software without bugs, we must always assume there are bugs in our software. Subsequently, it would be very nice if we would be aware of those bugs as well. We cannot always be aware of all the bugs in our software, but we can be aware of all exceptions that occur in our software, using logging and telemetrics services.
One of those services is Azure’s Application Insights which, among doing many other things, can collect browser exceptions coming from Javascript-based single page applications and provide much useful information about them.
Posts
Render children in an Angular wrapper component using ng-content
In my past experience with React, I have always used props.children to render children inside a wrapper or style component. It would look something like this:
// Wrapper component: function WrapperComponent(props) { return <div class="wrapper">{{ props.children }}</div> } // Usage: function AppComponent() { return <WrapperComponent><div id="child">I'm a child</div></Wrapper> } Now, as I’m working with Angular, I needed to do the same thing. However, I could never find the correct way to do it.
Posts
Angular :host in css
So I was working on creating a nice extendable skeleton image/svg+xml component when I stumbled upon a problem: I wanted to create a base skeleton style for the component that could be extended outside the component using utility classes. Something like this:
// Skeleton template <div class="skeleton"></div> // Skeleton CSS .skeleton { background: lightgray; width: 100%; height: 1em; // etc. } // Implementation of skeleton component // with utility classes <app-skeleton class="rounded p-1"></app-skeleton> However, what happened during runtime was the following:
Tag: animations
Posts
Square loading favicon in Typescript
Based on rpsthecoder’s square loading favicon image/svg+xml in JavaScript, but now in proper Typescript.
/** * Square loading favicon in Typescript * Author: Drikus Roor * Original author: https://github.com/rpsthecoder/square-loading-favicon */ interface IFavicon extends Element { href: string; } export function animateFavicon() { const canvas = document.querySelector("canvas"); if (!canvas) { return; } const context = canvas.getContext("2d"); if (context) { const favicon = document.
Tag: apache
Posts
Force HTTPS on your WordPress website
You have finally installed that SSL certificate to your website and now the website keeps hanging in an unsafe http connection. What is up with that?
To force a HTTPS connection, we only have to add some lines to the .htaccess file, which is located in the root of the public html folder of your WordPress website:
.htaccess is located in the public html folder of your WordPress website, which is the same folder that contains the wp-admin, wp-content, and wp-includes folder.
Tag: app-service
Posts
Host a static Angular build in an Azure App Service
Building an Angular app usually results in a bunch of files, mainly consisting of Javascript files, CSS files, and an index.html.
An Azure App Service normally wants to host an application using a startup command for a specific stack (PHP, Node, Python, etc.).
Technically, you could run your Angular app as a Node app. In that case you would run npm run start or ng serve as the startup command.
Tag: application-insights
Posts
Log errors to Azure Application Insights from an Angular app
As there is no software without bugs, we must always assume there are bugs in our software. Subsequently, it would be very nice if we would be aware of those bugs as well. We cannot always be aware of all the bugs in our software, but we can be aware of all exceptions that occur in our software, using logging and telemetrics services.
One of those services is Azure’s Application Insights which, among doing many other things, can collect browser exceptions coming from Javascript-based single page applications and provide much useful information about them.
Tag: azure
Posts
SQL error with code 40531 when trying to fetch schema in Azure Database Sync
As I was trying to sync my Hub database to my Member database in Azure Database Sync, I got this error when trying to fetch the schema of the Hub database:
Getting schema information for the database failed with the exception "Failed to connect to server databasename-0182730712073.database.windows.net.Inner exception: SqlException ID: {someGuid}, Error Code: -2146232060 - SqlError Number:40531, Message: SQL error with code 40531 For more information, provide tracing ID ‘{someGuid}’ to customer support.
Posts
Create an Azure SQL Server login and connect a user to it
In my previous post image/svg+xml I showed how you can convert a .bak file to a DAC file and how to fix any errors that may appear. For the same job, I had to add some new SQL logins and users after the migration of the database. This post serves as a notebook for how to do that.
\-- Execute this query in the "master" database -- Create new login CREATE LOGIN \[new-login\] WITH PASSWORD = 'complex-password' GO -- Execute these queries in the target database -- Create a user and connect it to the login CREATE USER \[new-user\] FOR LOGIN \[new-login\] -- Create a role to execute stored procedures CREATE ROLE \[db\_executor\] AUTHORIZATION \[dbo\] GO GRANT EXECUTE TO \[db\_executor\] GO -- Give the user read/write/execute rights sp\_addrolemember @rolename = 'tc\_execute', @membername = 'new-user' GO sp\_addrolemember @rolename = 'db\_datareader', @membername = 'new-user' GO sp\_addrolemember @rolename = 'db\_datawriter', @membername = 'new-user' GO -- Check if roles have been assigned to the user correctly SELECT UserType='Role', DatabaseUserName = '{Role Members}', LoginName = DP2.
Posts
Fix a SQL database before exporting to a DAC .bacpac file
When you want to migrate an old (on-premise) SQL database to an Azure SQL database, you need to export the database to a DAC .bacpac file. Such an export also includes schemas, views and users/logins. It is easy to receive errors when attempting to make a .bacpac export. In this post, I sum up the errors I received and a way to fix them.
1. Drop Windows users In my case, the database that I wanted to migrate contained references to Windows users.
Posts
Host a static Angular build in an Azure App Service
Building an Angular app usually results in a bunch of files, mainly consisting of Javascript files, CSS files, and an index.html.
An Azure App Service normally wants to host an application using a startup command for a specific stack (PHP, Node, Python, etc.).
Technically, you could run your Angular app as a Node app. In that case you would run npm run start or ng serve as the startup command.
Posts
Log errors to Azure Application Insights from an Angular app
As there is no software without bugs, we must always assume there are bugs in our software. Subsequently, it would be very nice if we would be aware of those bugs as well. We cannot always be aware of all the bugs in our software, but we can be aware of all exceptions that occur in our software, using logging and telemetrics services.
One of those services is Azure’s Application Insights which, among doing many other things, can collect browser exceptions coming from Javascript-based single page applications and provide much useful information about them.
Posts
Prevent your blob storage from storing too many blobs
I host my Angular websites using Azure and I use Application Insights to find and report errors. Normally, the exception gets logged, but Angular builds usually have minified javascript, making it hard to debug the origin of an error.
Luckily, Azure support uploading the sourcemaps of a minified Javascript bundle to a Azure Blob Storage Container, which can then be used by Azure’s Application Insights to un-minify the stack trace of an error.
Posts
Update Azure Alert Rule Condition Query
For a lot of people probably a piece of cake, but I had to look a while before I could find it.
In Azure Portal, go to Alerts.
Go to Manage alert rules.
App names are hidden because of privacy reasons
Go to the application for which you want to edit the query.
Click on the condition whose query needs to be edited.
Posts
How to make an Azure Function App read Secrets from a Key Vault
1. Make sure the function app has a managed identity Go to your Azure Function App and then go to Settings > Identity. Switch the status from off to on.
Enabling System assigned managed identity in the Azure Function App
2. Create a Secret in the Azure Key Vault Go to your Azure Key Vault and then go to Settings > Secrets. Click + Generate/Import.
Navigating towards Secrets in the Azure Key Vault
Tag: bacpac
Posts
Fix a SQL database before exporting to a DAC .bacpac file
When you want to migrate an old (on-premise) SQL database to an Azure SQL database, you need to export the database to a DAC .bacpac file. Such an export also includes schemas, views and users/logins. It is easy to receive errors when attempting to make a .bacpac export. In this post, I sum up the errors I received and a way to fix them.
1. Drop Windows users In my case, the database that I wanted to migrate contained references to Windows users.
Tag: behat
Posts
Behat: context class not found and can not be used.
If you are using Behat for testing your PHP application and you encounter the following error after trying to run your tests:
In UninitializedContextEnvironment.php line 44: Tests\\Feature\\Behat\\Context\\Account\\MyOldContext\\ context class not found and can not be used. Do not forget to remove your obsolete Behat Context file (MyOldContext in this case) from your behat.yml configuration file:
default: suites: default: paths: - '%paths.base%/tests/Feature/Behat/features' contexts: - Tests\\Feature\\Behat\\Context\\ApplicationContext # Remove the old context file - Tests\\Feature\\Behat\\Context\\MyOldContext - Tests\\Feature\\Behat\\Context\\EmailContext - Behat\\MinkExtension\\Context\\MinkContext - behatch:context:browser - behatch:context:debug - behatch:context:system - behatch:context:json - behatch:context:rest
Tag: blob-storage
Posts
Prevent your blob storage from storing too many blobs
I host my Angular websites using Azure and I use Application Insights to find and report errors. Normally, the exception gets logged, but Angular builds usually have minified javascript, making it hard to debug the origin of an error.
Luckily, Azure support uploading the sourcemaps of a minified Javascript bundle to a Azure Blob Storage Container, which can then be used by Azure’s Application Insights to un-minify the stack trace of an error.
Tag: camera
Posts
Turn off Oblivion head bobbing
Every now and then I like to play my beloved Oblivion. To keep things interesting I have installed quite some mods over the years. At one point, however, my head started bobbing while walking and it seemed like I was in crouching mode when standing still. The problem persisted even until after I installed all my mods. Eventually I found the culprit, but to help other possible victims, I will list possible solutions to the problem of not being able to turn off head bobbing:
Tag: canvas
Posts
Square loading favicon in Typescript
Based on rpsthecoder’s square loading favicon image/svg+xml in JavaScript, but now in proper Typescript.
/** * Square loading favicon in Typescript * Author: Drikus Roor * Original author: https://github.com/rpsthecoder/square-loading-favicon */ interface IFavicon extends Element { href: string; } export function animateFavicon() { const canvas = document.querySelector("canvas"); if (!canvas) { return; } const context = canvas.getContext("2d"); if (context) { const favicon = document.
Tag: chatgpt
Posts
Simple GPT CLI
Using my friend ChatGPT I made a little CLI to talk to… GPT. It’s basically a bash script that you can place in one of you bin folders and execute from wherever in your terminal:
gpt "I need a new cactus, what is a nice type that needs little maintenance?" After which GPT will answer you with (hopefully) a nice answer:
GPT-3 answers: One type of cactus that is low-maintenance is the Peruvian apple cactus.
Posts
A ChatGPT prompt generation script to summarize & review the code changes between two branches
summareview.sh #!/bin/bash # This script will help you to generate a ChatGPT prompt that you can use to summarize and review the changes between two branches. # It will prompt you for the feature branch, the branch to compare to, the ticket/story/bug description, and any additional feedback. # It will then output the changes and the prompt to a file called summareview.txt. # Get the current branch current_branch=$(git rev-parse --abbrev-ref HEAD) # Prompt for feature branch (default: current branch) read -p "Enter the feature branch to compare (default: $current_branch): " feature_branch feature_branch=${feature_branch:-$current_branch} # Prompt for branch to compare to (default: develop) read -p "Enter the branch to compare to (default: develop): " compare_branch compare_branch=${compare_branch:-develop} # Prompt for ticket/story/bug description read -p "Enter the ticket/story/bug description: " ticket_description # Prompt for additional feedback read -p "Enter any additional feedback (optional): " additional_feedback # Execute git log command and store the output in a variable git_log_output=$(git log $compare_branch.
Posts
Highlight search terms in Wordpress
To highlight search terms in the content in your Wordpress search result page, add the following function to your functions.php file:
function search_excerpt_highlight() { $content = get_the_content(); $content = wp_strip_all_tags($content); // Set the excerpt length $excerpt_length = 100; // You can adjust this value to your desired excerpt length $padding = 10; // Add padding around the search term $keys = explode(' ', get_search_query()); $first_key = $keys[0]; // Find the first occurrence of the search term $term_pos = stripos($content, $first_key); if ($term_pos !
Tag: child-theme
Posts
How to quickly add multiple colors to your Wordpress theme customizer
I am currently working on dark mode support for a Wordpress theme. For that, the website will need to use different colors depending on the preference of the user. At the same time, I want those colors to be easily customizable through Wordpress' Customizer.
What I don’t want, however, is 500 lines of code just to add a few colors. The hooks for adding Wordpress customizer settings image/svg+xml and controls image/svg+xml are no one-liners.
Posts
Organize your Wordpress theme's functions.php by using namespaces and classes
As you can extend your Wordpress theme by adding actions to the theme’s functions.php, it is safe to say that it is very easy to bloat this file with hundreds of lines of code.
The nasty thing is that the usual advice is to write a function and then add that function as an action by passing the function’s name as a string. That would look something like this:
<?php // file: functions.
Posts
Add and display a setting to your Wordpress child theme
My client asked me to show a short message above every page and post and wished to be able to modify this text himself through the theme customizer.
Now, this is not too hard and I have done it multiple times before, but I keep forgetting the specifics. This post is therefore meant as a quick cheatsheet for myself, but maybe it will help you, anonymous internet user, as well.
Posts
Combine custom post types in one blog page
If you, like me, are using Pods image/svg+xml to create custom post types, you might have noticed that the post types created using Pods do not appear on your blog page by default. This is because Wordpress only queries posts with the post type post by default.
Now, you may not even want to display your pods on the blog page, but if you do, there are several ways to do this (and the choice is yours).
Posts
Copy and modify the custom header of a Wordpress parent theme to a child theme
For a client I am currently creating a new website in Wordpress. To speed up design, I am basing my own Wordpress theme on an existing theme: Twenty Thirteen image/svg+xml . It is fairly old already (2013), but I like the general layout with a header and navigation on top.
Whenever you upload a header image in this theme, the image would be displayed over the full width of the page.
Tag: cms
Posts
How to use Notion as a CMS for a Hugo powered statically generated site
This website is created using Hugo, the static site generator. I use Markdown for the posts. These posts exist in a Github repository. Github Actions then makes sure the site gets generated and deployed every time I make a commit. However, for a new post I have to open my code editor and start writing in Markdown. This can be a hassle sometimes.
It would be great if there was a way to create new posts without having to open my code editor.
Tag: code-coverage
Posts
Where is Gitlab's test coverage parsing setting
Today, I wanted to set the regular expression for my test coverage results in Gitlab.
According to Gitlab’s documentation image/svg+xml , I should be able to do that in the test coverage parsing setting in my project settings, by navigating to Settings > CI/CD > General pipelines.
Problem However, I could not find the setting there. So where can I set the regular expression for the test coverage parsing setting in Gitlab?
Tag: commands
Posts
Repository of convenient terminal commands
This article will be filled with convenient terminal commands for my own reference.
Logs Check latest logs in linux Navigation journalctl -xe Go back to previous location cd - Other List all services service --status-all Permissions Show read / write permissions as numbers find . -maxdepth 1 -printf "%m %f\\n" Services See under which user a service is running ps -ef
Tag: configuration
Posts
Check if a Wordpress constant has been defined
Suppose I have configured a constant in the wp-config.php of my website:
<?php /\* Super important configuration constant \*/ define('SUPER\_IMPORTANT\_VALUE', '123e4567-e89b-12d3-a456-426614174000'); ?>Whenever you want to use this value in your website, it would be nice to know if the constant has been defined already. You’d expect to be able to do this using something like:
<?php /\* !empty does not work for a constant \*/ if (!empty(SUPER\_IMPORTANT\_VALUE)) { // Do stuff } ?
Tag: constants
Posts
Check if a Wordpress constant has been defined
Suppose I have configured a constant in the wp-config.php of my website:
<?php /\* Super important configuration constant \*/ define('SUPER\_IMPORTANT\_VALUE', '123e4567-e89b-12d3-a456-426614174000'); ?>Whenever you want to use this value in your website, it would be nice to know if the constant has been defined already. You’d expect to be able to do this using something like:
<?php /\* !empty does not work for a constant \*/ if (!empty(SUPER\_IMPORTANT\_VALUE)) { // Do stuff } ?
Tag: css
Posts
Use a fallback for Safari’s problematic mix-blend-mode implementation, in TailwindCSS
Recently I had been working on a website that uses mix-blend-mode: color. I just found out it didn’t work on Safari. Apparently color is not supported image/svg+xml . I had to find a way to maintain this mix blend mode for non-Safari browsers, in which it worked fine, but override it in Safari.
Then I found this overly verbose answer image/svg+xml on Stackoverflow.
Posts
Prevent a flex button to take up full width
Regular html & css <style> .container { display: flex; flex-direction: column; } .item { display: flex; flex-direction: row; align-items: center; align-self: center; } </style> <body> <div class="container"> <button class="item"> <span>Click me!</span> <i>Icon</i> </button> </div> </body> Or with TailwindCSS <body> <div class="flex flex-col"> <button class="flex flex-row items-center self-center"> <span>Click me!</span> <i>Icon</i> </button> </div> </body> See also https://stackoverflow.com/a/67819933/4496102 image/svg+xml
Posts
Reload css stylesheet without reloading the page
Sometimes, a local development environment can be really slow at reloading pages. If you are working on styling a page or component and you want to check your changes, every page refresh generates frustration.
You can then also opt for only reloading the stylesheets of a page. This will likely be significantly faster. You can do this by using the following command in the console of your browser’s development tools:
Posts
A very simple animated skeleton gist
Just for my own reference, I will publish the skeleton css gist image/svg+xml I use in many of my projects here. It is very easy to use and very easy to extend with new shapes. You can check the --card and --rounded modifiers image/svg+xml for inspiration.
In Sass:
.skeleton { display: inline-block; height: 1em; position: relative; overflow: hidden; background-color: #dddbdd; &::after { position: absolute; top: 0; right: 0; bottom: 0; left: 0; transform: translateX(-100%); background-image: linear-gradient( 90deg, rgba(#fff, 0) 0, rgba(#fff, 0.
Posts
Angular :host in css
So I was working on creating a nice extendable skeleton image/svg+xml component when I stumbled upon a problem: I wanted to create a base skeleton style for the component that could be extended outside the component using utility classes. Something like this:
// Skeleton template <div class="skeleton"></div> // Skeleton CSS .skeleton { background: lightgray; width: 100%; height: 1em; // etc. } // Implementation of skeleton component // with utility classes <app-skeleton class="rounded p-1"></app-skeleton> However, what happened during runtime was the following:
Tag: custom-blocks
Posts
Wordpress custom blocks: Pass down attributes to child blocks
Suppose you are working on a set of interacting custom blocks in Wordpress. You have a child block that needs information from the parent block to display, in this situation, information about a specific record. In such a case you want to use Block context image/svg+xml .
Block context is a feature which enables ancestor blocks to provide values which can be consumed by descendent blocks within its own hierarchy.
Posts
Add JavaScript to a custom block in Wordpress
Using Wordpress custom blocks, I’m currently trying to create a popover component that contains a button and a hidden content. The hidden content should appear when the user clicks on or hovers over the button (on the frontend of the website, not in the block editor).
Problem However, when I add an onClick or onHover to the button, the event handler is not executed.
Additionally, trying to use the useState hook to store the display state of the popover crashes my block editor.
Tag: customizer
Posts
Add and display a setting to your Wordpress child theme
My client asked me to show a short message above every page and post and wished to be able to modify this text himself through the theme customizer.
Now, this is not too hard and I have done it multiple times before, but I keep forgetting the specifics. This post is therefore meant as a quick cheatsheet for myself, but maybe it will help you, anonymous internet user, as well.
Tag: dark-mode
Posts
Vue.js with dark mode while taking system preference and user preference into account
tl;dr - A vue.js example of adding dark mode support to your website that takes system preference and user preference into account. See link image/svg+xml for source.
When you are developing a website with dark-mode support, there are usually two paths you can take:
Use the [prefers-color-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme) CSS media feature and thereby use the system preference. Use a website setting to set a .
Tag: debug
Posts
Debug PHPUnit in Docker using PHPStorm
Problem I have a Docker setup that consists of:
A container that runs PHP A container that runs a MySQL database I am using PHPStorm for development and I would like to debug my PHPUnit tests that run inside of Docker container #1. However, when I try to do this, I get an error:
PDOException : SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo for tms-api-mysql failed: Name or service not known /var/www/html/vendor/illuminate/database/Connectors/Connector.
Tag: docker
Posts
Debug PHPUnit in Docker using PHPStorm
Problem I have a Docker setup that consists of:
A container that runs PHP A container that runs a MySQL database I am using PHPStorm for development and I would like to debug my PHPUnit tests that run inside of Docker container #1. However, when I try to do this, I get an error:
PDOException : SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo for tms-api-mysql failed: Name or service not known /var/www/html/vendor/illuminate/database/Connectors/Connector.
Posts
phpMyAdmin - Error | Incorrect format parameter
If you are ever trying to import a (large) existing database through phpMyAdmin and you are getting the following error, you might want to check your php.ini file.
\# File: php.ini memory\_limit = 256M post\_max\_size = 128M upload\_max\_filesize = 128M max\_execution\_time = 600 max\_input\_time = 600 Try increasing the values image/svg+xml of the configuration variables until you get successful results.
If you are using Docker to boot up your phpMyAdmin instance, you might also want to check the UPLOAD_LIMIT environment variable in your docker-compose.
Tag: doctrine
Posts
Base table or view not found: 1146 Table doesn't exist
When trying to use a Filament resource while also using Doctrine as an ORM, one might encounter the following error:
Illuminate\Database\QueryException SQLSTATE[42S02]: Base table or view not found: 1146 Table 'underhold.suppliers' doesn't exist (SQL: select * from `suppliers` where `id` = 8 limit 1) http://localhost/admin/resources/suppliers/8/edit In my case, the database table did not have a plural name and was simply named supplier. To let filament know what the correct table name is, I extended my model from Eloquent and specified the table name from within the model:
Tag: dotnet
Posts
Sort list of lists in dotnet core
using System; using System.Text.Json; var array = JsonSerializer.Deserialize<List<List<int>>>("[[3, 2], [1, 1], [0,3],[0,2],[0,1], [1,3], [1,2], [2, 3]]"); Console.WriteLine(JsonSerializer.Serialize(array)); // [[3,2],[1,1],[0,3],[0,2],[0,1],[1,3],[1,2],[2,3]] var sorted = array.OrderBy(y => y[0]).ThenBy(y => y[1]); Console.WriteLine(JsonSerializer.Serialize(sorted)); // [[0,1],[0,2],[0,3],[1,1],[1,2],[1,3],[2,3],[3,2]] Source image/svg+xml
Posts
Test multiple SQL Server connection strings in a dotnet console app
As I have explained how to create some new logins and users in my previous post image/svg+xml , I now had to create some connection strings for those logins. To check if all logins were created successfully, I have created a small dotnet console application to test out the connection strings associated with these logins:
using System.Data.SqlClient; class Credentials { public string Username { get; set; } public string Password { get; set; } public string Server { get; set; } public Credentials(string username, string password, string server = "sql-server.
Posts
IOException: Permission denied for .NET application running as a linux service
For an upload feature, my .NET application needs to upload a file to a newly created directory. My application is running as a linux service. Whenever the application tries to create a folder and add the file, I get an IOException:
An unhandled exception occurred while processing the request. IOException: Permission denied.
At first, I though I’d just chmod 777 the /var/bots folder and give full write permissions. It worked, but it would probably not be a viable and secure solution for the long term.
Posts
Github OAuth redirect_uri_mismatch for .NET App behind a Nginx Reverse Proxy
Let’s say we have a .NET app running on an virtual machine. The app uses Github OAuth for authentication. Inside the virtual machine, the app runs on http://127.0.0.1:5000. The app should be available on https://example.com, so I have created an entry in nginx to send all requests towards https://example.com to http://127.0.0.1:5000:
server { server\_name example.org www.example.org; listen 80; listen 443; location / { proxy\_pass https://127.0.0.1:5001/; } } So this works. My website can be reached from https://example.
Tag: email
Posts
Wordpress cannot send emails to email addresses on its own domain
Imagine the following situation: You have a Wordpress website hosted on example.com. The host has a Plesk configuration panel. Your email is handled by Google Workspace. MX records have been configured for this in Plesk, as described here image/svg+xml . The website has a contact form that should send an email to you, the owner of the website, on info@example.com.
But… the emails are not arriving.
Tag: emit
Posts
Test vue component event emits
const WrapperComponent = { components: { ChildComponent, }, methods: { onUpdate: jest.fn(), }, template: '<child-component @onUpdate="onUpdate" />', }; describe('ChildComponent', () => { let wrapper; beforeEach(() => { wrapper = mount(WrapperComponent, {}); }); afterEach(() => { wrapper.destroy(); }); it('emits onUpdate event', async () => { const spy = jest.spyOn(WrapperComponent.methods, 'onUpdate'); // do something that would make child component emit the 'onUpdate' event expect(spy).toHaveBeenCalled(); }); });
Tag: eslint
Posts
Format code on save using ESLint and VS Code
I have always had problems when combining Prettier image/svg+xml and ESLint image/svg+xml the same project in VS Code. Prettier would not respect my ESLint rules or vice versa. Sometimes I could mitigate the problems by using the eslint-config-prettier package in my ESLint configuration.
But now, thanks to James Quick image/svg+xml I’ve found a way to get rid of Prettier while still having the format on save feature in VS Code.
Posts
Handle imports without extensions in Vue.js 2
If you want to import your Vue components in the following way, so without a .vue or .js extension:
import CrazyComponent from '@/components/CrazyComponent'; // instead of import CrazyComponent from '@/components/CrazyComponent.vue'; There are some things you have to configure. I will outline these things below:
Rollup Add the following to your rollup.config.js:
nodeResolve({ browser: true, jsnext: true, main: true, extensions: ['.js', '.vue'] }), ESLint Add the following to your eslintrc.
Posts
Use aliases in Vue.js imports
I don’t like to do relative imports like this:
import CrazyComponent from "../../components/CrazyComponent"; Instead, I like to import my components (stores, helpers, models, etc.) like this:
import CrazyComponent from "@/components/CrazyComponent"; You might want to configure some stuff to make this possible. I will outline these configurations below:
ESLint First, install eslint-import-resolver-custom-alias:
npm install eslint-import-resolver-custom-alias --save-dev In your eslintrc.js or the eslintConfig section in your package.json, add the following resolver under "import/resolver".
Tag: event
Posts
Test vue component event emits
const WrapperComponent = { components: { ChildComponent, }, methods: { onUpdate: jest.fn(), }, template: '<child-component @onUpdate="onUpdate" />', }; describe('ChildComponent', () => { let wrapper; beforeEach(() => { wrapper = mount(WrapperComponent, {}); }); afterEach(() => { wrapper.destroy(); }); it('emits onUpdate event', async () => { const spy = jest.spyOn(WrapperComponent.methods, 'onUpdate'); // do something that would make child component emit the 'onUpdate' event expect(spy).toHaveBeenCalled(); }); });
Tag: filament
Posts
Base table or view not found: 1146 Table doesn't exist
When trying to use a Filament resource while also using Doctrine as an ORM, one might encounter the following error:
Illuminate\Database\QueryException SQLSTATE[42S02]: Base table or view not found: 1146 Table 'underhold.suppliers' doesn't exist (SQL: select * from `suppliers` where `id` = 8 limit 1) http://localhost/admin/resources/suppliers/8/edit In my case, the database table did not have a plural name and was simply named supplier. To let filament know what the correct table name is, I extended my model from Eloquent and specified the table name from within the model:
Tag: file-permissions
Posts
Joomla: JFolder::create: Infinite loop detected.
Today, I tried to install an extension to a Joomla website I am currently working on. However, I got an error message, saying:
Warning Joomla\CMS\Filesystem\Folder::create: Infitinite loop detected. Error Unable to find install package
A quick search on Google taught me it has something to do with the file permissions on the logs and tmp folders. They need to be writable. So, using Filezilla, I set the file permissions of these folders to 777:
Tag: flexbox
Posts
Prevent a flex button to take up full width
Regular html & css <style> .container { display: flex; flex-direction: column; } .item { display: flex; flex-direction: row; align-items: center; align-self: center; } </style> <body> <div class="container"> <button class="item"> <span>Click me!</span> <i>Icon</i> </button> </div> </body> Or with TailwindCSS <body> <div class="flex flex-col"> <button class="flex flex-row items-center self-center"> <span>Click me!</span> <i>Icon</i> </button> </div> </body> See also https://stackoverflow.com/a/67819933/4496102 image/svg+xml
Tag: flywheel-local-2
Posts
How to keep Flywheel Local and your repository separated using symlinks
Since a while, I have been using Flywheel’s Local for my local WordPress development server and it has been. No time spend on configuration Docker, Apache, database connections, et cetera.
However, one thing that has been bugging me is the question of how to combine Local’s configuration and my own code, which contains my WordPress themes and plugins. As Local creates its own WordPress folders (wp-content etc.) inside its configuration folders, how should I approach such a situation?
Tag: font-awesome
Posts
React & Tailwind CSS Tooltip Component
Tooltip component export function Tooltip({ content }) { return ( {/* Tailwind's group class will be used trigger the hover */} <span className="group"> {/* Font Awesome question mark icon */} <i className="fas fa-question-circle text-black group-hover:scale-120 ml-1 cursor-pointer ease-in-out duration-300 transition-transform"></i> <span className={` w-full absolute rounded shadow text-sm font-normal font-sans bg-black text-white p-2 pointer-events-none group-hover:pointer-events-auto opacity-0 group-hover:opacity-100 left-0 -top-3 -translate-y-3/4 group-hover:-translate-y-full ease-in-out duration-300 transition-[transform,opacity]`} > {/* Set inner HTML or just output content in an expression */} <span dangerouslySetInnerHTML={{ __html: content }}></span> {/* Optional speech balloon triangle pointing down */} <div className={` absolute w-0 h-0 border-l-4 border-t-4 border-r-4 border-b-4 border-black left-1/2 -translate-x-2 -bottom-1 transform rotate-45 shadow`} ></div> </span> </span> ); } How to use Tooltip import { Tooltip } from ".
Tag: function-app
Posts
How to make an Azure Function App read Secrets from a Key Vault
1. Make sure the function app has a managed identity Go to your Azure Function App and then go to Settings > Identity. Switch the status from off to on.
Enabling System assigned managed identity in the Azure Function App
2. Create a Secret in the Azure Key Vault Go to your Azure Key Vault and then go to Settings > Secrets. Click + Generate/Import.
Navigating towards Secrets in the Azure Key Vault
Tag: gdrp
Posts
Customizable javascript cookie banner
class CookieBanner { dropCookie = true; // false disables the Cookie, allowing you to style the banner cookieDuration = 14; // Number of days before the cookie expires, and the banner reappears cookieName = 'complianceCookie'; // Name of our cookie cookieValue = 'on'; // Value of cookie initialBodyPaddingTop = 0; message = 'Our website uses cookies. By continuing we assume your permission to deploy cookies, as detailed in our {{privacyPolicy}}.
Tag: gist
Posts
A ChatGPT prompt generation script to summarize & review the code changes between two branches
summareview.sh #!/bin/bash # This script will help you to generate a ChatGPT prompt that you can use to summarize and review the changes between two branches. # It will prompt you for the feature branch, the branch to compare to, the ticket/story/bug description, and any additional feedback. # It will then output the changes and the prompt to a file called summareview.txt. # Get the current branch current_branch=$(git rev-parse --abbrev-ref HEAD) # Prompt for feature branch (default: current branch) read -p "Enter the feature branch to compare (default: $current_branch): " feature_branch feature_branch=${feature_branch:-$current_branch} # Prompt for branch to compare to (default: develop) read -p "Enter the branch to compare to (default: develop): " compare_branch compare_branch=${compare_branch:-develop} # Prompt for ticket/story/bug description read -p "Enter the ticket/story/bug description: " ticket_description # Prompt for additional feedback read -p "Enter any additional feedback (optional): " additional_feedback # Execute git log command and store the output in a variable git_log_output=$(git log $compare_branch.
Posts
Insert a Google Analytics sitetag in Wordpress using a constant defined in wp-config.php
First, define your Google Analytics constant in wp-config.php:
// wp-config.php /\* Google Analytics Key \*/ define('GOOGLE\_ANALYTICS\_KEY', 'G-XXXXXXXXXX'); Then, insert the following gist inside the <head> of your website (header.php in my case):
// header.php (for example) <?php if (defined('GOOGLE\_ANALYTICS\_KEY')) { ?><!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo GOOGLE\_ANALYTICS\_KEY; ?>"></script> <script> window.dataLayer = window.dataLayer || \[\]; function gtag() { dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', '<?
Posts
A very simple animated skeleton gist
Just for my own reference, I will publish the skeleton css gist image/svg+xml I use in many of my projects here. It is very easy to use and very easy to extend with new shapes. You can check the --card and --rounded modifiers image/svg+xml for inspiration.
In Sass:
.skeleton { display: inline-block; height: 1em; position: relative; overflow: hidden; background-color: #dddbdd; &::after { position: absolute; top: 0; right: 0; bottom: 0; left: 0; transform: translateX(-100%); background-image: linear-gradient( 90deg, rgba(#fff, 0) 0, rgba(#fff, 0.
Tag: git
Posts
A first encounter with ChatGPT
The arrival of DALL-E 2, Stable Diffusion, and GPT-3 has opened up a new world for developers, data scientists, and other tech adepts. These powerful AI models are capable of generating images, text, and other data in a wide range of styles and formats, and they offer exciting new possibilities for a variety of applications.
One of the most exciting developments in this field is ChatGPT, an AI model that is trained to generate conversational text in a natural and engaging way.
Tag: github
Posts
How to add a search bar to an Upptime status page
Upptime image/svg+xml is a very neat tool that allows you to track the status of your websites and creates Github issues whenever a site has downtime. The extra neat aspect of Upptime is that it works entirely on Github. No hosting or cloud provider is necessary whatsoever, it all runs using Github Actions and Github Pages.
Upptime is not perfect (yet) though. It misses some features that would make it perfect for me.
Tag: gitlab
Posts
Gitlab CI/CD job is not showing up
This happened to me today: A Gitlab CI/CD job in a valid stage without any dependencies or rules was not showing up in my Gitlab CI/CD pipeline. It looked like this:
# Incorrect, job does NOT show up in pipeline as it is seen as a job template .e2e: image: cypress/browsers:node12.14.1-chrome85-ff81 stage: .post artifacts: when: always paths: - cypress/videos/**/*.mp4 - cypress/screenshots/**/*.png expire_in: 3 day script: - npm ci - npm run test:e2e After some experimenting I found out that the name of the job was the culprit.
Posts
Where is Gitlab's test coverage parsing setting
Today, I wanted to set the regular expression for my test coverage results in Gitlab.
According to Gitlab’s documentation image/svg+xml , I should be able to do that in the test coverage parsing setting in my project settings, by navigating to Settings > CI/CD > General pipelines.
Problem However, I could not find the setting there. So where can I set the regular expression for the test coverage parsing setting in Gitlab?
Posts
Setup Gitlab token for private composer packages
Have you ever received the following error?
[Composer\Downloader\TransportException] The "https://gitlab.my-gitlab-instance.com/api/v4/group/666/-/packages/composer/packages.json" file could not be downloaded (HTTP/2 404 ): {"message":"404 Group Not Found"} I have, and it has kept me from doing my work several times. The readme files of several projects give some attention to this issue, but you might not be working in those specific projects when you encounter these terrible issues. This is why I wrote this short instructions post on Confluence; hopefully Confluence’s search feature will find this post everytime I (or you) run into the same ol' story and forget how to solve it.
Posts
Update the PUBLIC_URL environment variable in Gitlab's CI for a React website hosted in a subfolder
When hosting a React website in a subfolder, you want the paths to the images and fonts to be updated as well. When the path of an image in your development environment is /images/background.jpg and your website is hosted at https://example.com/app, you want the path to be updated to /app/images/background.jpg in the production build.
You can do this using the PUBLIC_URL environment variable image/svg+xml .
Tag: google-analytics
Posts
Insert a Google Analytics sitetag in Wordpress using a constant defined in wp-config.php
First, define your Google Analytics constant in wp-config.php:
// wp-config.php /\* Google Analytics Key \*/ define('GOOGLE\_ANALYTICS\_KEY', 'G-XXXXXXXXXX'); Then, insert the following gist inside the <head> of your website (header.php in my case):
// header.php (for example) <?php if (defined('GOOGLE\_ANALYTICS\_KEY')) { ?><!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo GOOGLE\_ANALYTICS\_KEY; ?>"></script> <script> window.dataLayer = window.dataLayer || \[\]; function gtag() { dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', '<?
Tag: google-maps
Posts
Easy full-width embedded Google Maps in php
Just an easy full-width embedded Google Maps snippet image/svg+xml for my own reference:
<!-- In PHP --> <iframe src=" <?php $search\_terms = rawurlencode("3 Abbey Road, London, GB NW8 9AY"); $src = "https://www.google.com/maps?q=2880%20" . $search\_terms . "&t=&z=15&ie=UTF8&iwloc=&output=embed"; echo $src; ?>" width="600" height="500" style="border:0; width: 100% !important;" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" allowfullscreen="" loading="lazy"> </iframe> <!-- Or, in raw HTML --> <iframe src="https://www.google.com/maps?q=2880%203%20Abbey%20Road%2C%20London%2C%20GB%20NW8%209AY&t=&z=15&ie=UTF8&iwloc=&output=embed" style="border: 0px none; width: 100% !
Tag: gutenberg
Posts
Wordpress custom blocks: Pass down attributes to child blocks
Suppose you are working on a set of interacting custom blocks in Wordpress. You have a child block that needs information from the parent block to display, in this situation, information about a specific record. In such a case you want to use Block context image/svg+xml .
Block context is a feature which enables ancestor blocks to provide values which can be consumed by descendent blocks within its own hierarchy.
Posts
Add JavaScript to a custom block in Wordpress
Using Wordpress custom blocks, I’m currently trying to create a popover component that contains a button and a hidden content. The hidden content should appear when the user clicks on or hovers over the button (on the frontend of the website, not in the block editor).
Problem However, when I add an onClick or onHover to the button, the event handler is not executed.
Additionally, trying to use the useState hook to store the display state of the popover crashes my block editor.
Tag: head-bobbing
Posts
Turn off Oblivion head bobbing
Every now and then I like to play my beloved Oblivion. To keep things interesting I have installed quite some mods over the years. At one point, however, my head started bobbing while walking and it seemed like I was in crouching mode when standing still. The problem persisted even until after I installed all my mods. Eventually I found the culprit, but to help other possible victims, I will list possible solutions to the problem of not being able to turn off head bobbing:
Tag: html
Posts
Prevent a flex button to take up full width
Regular html & css <style> .container { display: flex; flex-direction: column; } .item { display: flex; flex-direction: row; align-items: center; align-self: center; } </style> <body> <div class="container"> <button class="item"> <span>Click me!</span> <i>Icon</i> </button> </div> </body> Or with TailwindCSS <body> <div class="flex flex-col"> <button class="flex flex-row items-center self-center"> <span>Click me!</span> <i>Icon</i> </button> </div> </body> See also https://stackoverflow.com/a/67819933/4496102 image/svg+xml
Tag: https
Posts
Force HTTPS on your WordPress website
You have finally installed that SSL certificate to your website and now the website keeps hanging in an unsafe http connection. What is up with that?
To force a HTTPS connection, we only have to add some lines to the .htaccess file, which is located in the root of the public html folder of your WordPress website:
.htaccess is located in the public html folder of your WordPress website, which is the same folder that contains the wp-admin, wp-content, and wp-includes folder.
Tag: hugo
Posts
How to use Notion as a CMS for a Hugo powered statically generated site
This website is created using Hugo, the static site generator. I use Markdown for the posts. These posts exist in a Github repository. Github Actions then makes sure the site gets generated and deployed every time I make a commit. However, for a new post I have to open my code editor and start writing in Markdown. This can be a hassle sometimes.
It would be great if there was a way to create new posts without having to open my code editor.
Posts
How to set the homepage cover image in the Ananke theme for Hugo
It is quite straightforward to set the cover image in Hugo’s Ananke theme. We store an image in the images folder of a post and set the featured_image variable to the images/cover.jpg path. The folder structure for a post then looks like this:
content - posts - first-post - images - cover.jpg - index.md And the post’s front matter image/svg+xml in first-post/index.md would look like this:
Tag: javascript
Posts
Customizable javascript cookie banner
class CookieBanner { dropCookie = true; // false disables the Cookie, allowing you to style the banner cookieDuration = 14; // Number of days before the cookie expires, and the banner reappears cookieName = 'complianceCookie'; // Name of our cookie cookieValue = 'on'; // Value of cookie initialBodyPaddingTop = 0; message = 'Our website uses cookies. By continuing we assume your permission to deploy cookies, as detailed in our {{privacyPolicy}}.
Tag: jest
Posts
Test vue component event emits
const WrapperComponent = { components: { ChildComponent, }, methods: { onUpdate: jest.fn(), }, template: '<child-component @onUpdate="onUpdate" />', }; describe('ChildComponent', () => { let wrapper; beforeEach(() => { wrapper = mount(WrapperComponent, {}); }); afterEach(() => { wrapper.destroy(); }); it('emits onUpdate event', async () => { const spy = jest.spyOn(WrapperComponent.methods, 'onUpdate'); // do something that would make child component emit the 'onUpdate' event expect(spy).toHaveBeenCalled(); }); });
Tag: joomla
Posts
Joomla: JFolder::create: Infinite loop detected.
Today, I tried to install an extension to a Joomla website I am currently working on. However, I got an error message, saying:
Warning Joomla\CMS\Filesystem\Folder::create: Infitinite loop detected. Error Unable to find install package
A quick search on Google taught me it has something to do with the file permissions on the logs and tmp folders. They need to be writable. So, using Filezilla, I set the file permissions of these folders to 777:
Tag: json
Posts
Quickly remove unwanted IDs in JSON
I am currently duplicating entities through an API and there is no duplicate feature yet. Therefore, I am copying the JSON output of an entity and using the POST method of the API to re-create it with a different ID. In order to avoid errors, I have to delete all IDs from the JSON. To do that, I have found a regex that helps me find all the "id": "{guid}" combinations that I can then replace with an empty string using VS Code or Notepad++.
Tag: key-vault
Posts
How to make an Azure Function App read Secrets from a Key Vault
1. Make sure the function app has a managed identity Go to your Azure Function App and then go to Settings > Identity. Switch the status from off to on.
Enabling System assigned managed identity in the Azure Function App
2. Create a Secret in the Azure Key Vault Go to your Azure Key Vault and then go to Settings > Secrets. Click + Generate/Import.
Navigating towards Secrets in the Azure Key Vault
Tag: keyboard
Posts
How to switch the Command (⌘) and the Option (⌥) keys on macOS
If you are working on Mac devices but you are using a keyboard with a Windows layout, you might have encountered this problem: You press the key combination Alt key + C to copy something, but it triggers Option + C, resulting in a confusing character appearing on your screen instead of the expected copy action. This can be a frustrating experience, especially for those who frequently switch between Mac and Windows environments.
Tag: laravel
Posts
How to mock a GuzzleHttp client that makes a request to a third-party API in a Laravel feature test?
In a Laravel project I have a feature test in which I test an internal endpoint. The endpoint has a Controller calls a method on a Service. The Service then tries to call a third-party endpoint. It is this third-party endpoint that I would like to mock.
I have looked at Guzzle’s documentation, but it seems like image/svg+xml the MockHandler strategy requires you to execute the http request inside of the test, which is not wat I want in my test.
Posts
Base table or view not found: 1146 Table doesn't exist
When trying to use a Filament resource while also using Doctrine as an ORM, one might encounter the following error:
Illuminate\Database\QueryException SQLSTATE[42S02]: Base table or view not found: 1146 Table 'underhold.suppliers' doesn't exist (SQL: select * from `suppliers` where `id` = 8 limit 1) http://localhost/admin/resources/suppliers/8/edit In my case, the database table did not have a plural name and was simply named supplier. To let filament know what the correct table name is, I extended my model from Eloquent and specified the table name from within the model:
Tag: line-breaks
Posts
Preserve line breaks from a textarea in Wordpress
Today, I have added some customization settings to a Wordpress website. One of these settings consisted of a textarea input that would be used to enter and display an address. When I wanted to display the address, however, the address was displayed as one single line where it should have been displayed on three lines (Street + number, postal code, city).
// Incorrect code: <?php $address = get\_theme\_mod('address', ''); if ($address) { echo $address; } ?
Tag: linux
Posts
IOException: Permission denied for .NET application running as a linux service
For an upload feature, my .NET application needs to upload a file to a newly created directory. My application is running as a linux service. Whenever the application tries to create a folder and add the file, I get an IOException:
An unhandled exception occurred while processing the request. IOException: Permission denied.
At first, I though I’d just chmod 777 the /var/bots folder and give full write permissions. It worked, but it would probably not be a viable and secure solution for the long term.
Tag: logging
Posts
Log errors to Azure Application Insights from an Angular app
As there is no software without bugs, we must always assume there are bugs in our software. Subsequently, it would be very nice if we would be aware of those bugs as well. We cannot always be aware of all the bugs in our software, but we can be aware of all exceptions that occur in our software, using logging and telemetrics services.
One of those services is Azure’s Application Insights which, among doing many other things, can collect browser exceptions coming from Javascript-based single page applications and provide much useful information about them.
Tag: macos
Posts
How to switch the Command (⌘) and the Option (⌥) keys on macOS
If you are working on Mac devices but you are using a keyboard with a Windows layout, you might have encountered this problem: You press the key combination Alt key + C to copy something, but it triggers Option + C, resulting in a confusing character appearing on your screen instead of the expected copy action. This can be a frustrating experience, especially for those who frequently switch between Mac and Windows environments.
Tag: modal
Posts
React modal component styled with TailwindCSS in TypeScript
This React component provides a flexible and animated modal dialog, using Tailwind CSS for styling. It’s designed to be easily integrated into any React project that already includes Tailwind CSS for its styling needs.
Features: Animations: Smooth transition for opening and closing the modal with fade and translation effects. Backdrop: Includes a clickable backdrop that closes the modal, enhancing the user experience and interaction. Accessibility: Implements focus management and can be closed with the Escape key, adhering to good accessibility practices.
Tag: mods
Posts
Turn off Oblivion head bobbing
Every now and then I like to play my beloved Oblivion. To keep things interesting I have installed quite some mods over the years. At one point, however, my head started bobbing while walking and it seemed like I was in crouching mode when standing still. The problem persisted even until after I installed all my mods. Eventually I found the culprit, but to help other possible victims, I will list possible solutions to the problem of not being able to turn off head bobbing:
Tag: mysql
Posts
Easy Node.js Mysql database table seeder
First, install npm dependencies:
npm i mysql2 @faker-js/faker dotenv Run the script with the command
node ./index.js Don’t forget to add the mysql db credentials to your .env file and of course edit the getSeedQuery function if you want to use it for your own table.
const mysql = require("mysql2"); const { faker } = require("@faker-js/faker"); require("dotenv").config(); function getSeedQuery(amount = 10000) { return Array.from({ length: amount }) .map(() => { const date = faker.
Posts
How not to get the row count in InnoDB MySQL
Yesterday I had to migrate a MySQL schema to a new server. Fun times. After I had finished the migration, I wanted to compare whether no data was lost. So I turned to Stackoverflow to find me a good MySQL command that would give me the row count of all tables in the schema so I could compare it to the schema on the old server. The command I used was:
Tag: nextjs
Posts
Throw error on missing environment variables in Next.js
Since this year I have been working on a new project for our client. A Next.js project for the first time in years. This morning I was having some problems as the Next.js website tried to fetch data from the API but receiving errors instead. A query variable in the URL was set to "undefined". After some poking around, I found out it was due to a missing environment variable in the project’s .
Tag: ng-content
Posts
Render children in an Angular wrapper component using ng-content
In my past experience with React, I have always used props.children to render children inside a wrapper or style component. It would look something like this:
// Wrapper component: function WrapperComponent(props) { return <div class="wrapper">{{ props.children }}</div> } // Usage: function AppComponent() { return <WrapperComponent><div id="child">I'm a child</div></Wrapper> } Now, as I’m working with Angular, I needed to do the same thing. However, I could never find the correct way to do it.
Tag: nginx
Posts
Github OAuth redirect_uri_mismatch for .NET App behind a Nginx Reverse Proxy
Let’s say we have a .NET app running on an virtual machine. The app uses Github OAuth for authentication. Inside the virtual machine, the app runs on http://127.0.0.1:5000. The app should be available on https://example.com, so I have created an entry in nginx to send all requests towards https://example.com to http://127.0.0.1:5000:
server { server\_name example.org www.example.org; listen 80; listen 443; location / { proxy\_pass https://127.0.0.1:5001/; } } So this works. My website can be reached from https://example.
Tag: node-js
Posts
Easy Node.js Mysql database table seeder
First, install npm dependencies:
npm i mysql2 @faker-js/faker dotenv Run the script with the command
node ./index.js Don’t forget to add the mysql db credentials to your .env file and of course edit the getSeedQuery function if you want to use it for your own table.
const mysql = require("mysql2"); const { faker } = require("@faker-js/faker"); require("dotenv").config(); function getSeedQuery(amount = 10000) { return Array.from({ length: amount }) .map(() => { const date = faker.
Posts
SyntaxError: Cannot use import statement outside a module
For the secret game I am developing, I needed a database to store User and Profile data. The game’s backend server is developed using Node.js and Typescript, and to simplify connecting to the MySQL database, I wanted to use TypeORM.
TypeORM is awesome. Previously, I had to create the database from scratch and I connected to the database directly and subsequently executed carefully prepared sql queries with parameters. With TypeORM I can specify entities, add columns with specific qualities.
Tag: notion
Posts
How to use Notion as a CMS for a Hugo powered statically generated site
This website is created using Hugo, the static site generator. I use Markdown for the posts. These posts exist in a Github repository. Github Actions then makes sure the site gets generated and deployed every time I make a commit. However, for a new post I have to open my code editor and start writing in Markdown. This can be a hassle sometimes.
It would be great if there was a way to create new posts without having to open my code editor.
Tag: npm
Posts
npm WARN old lockfile The package-lock.json file was created with an old version of npm
Recently, I’ve experienced this warning multiple times since I’ve installed a new version of Node.js and npm. Apparently we can update the version of the lockfile package-lock.json. It’s apparently quite easy to do. Just run:
npm install --package-lock-only Credits to this mothertrucker image/svg+xml
Posts
SyntaxError: Cannot use import statement outside a module
For the secret game I am developing, I needed a database to store User and Profile data. The game’s backend server is developed using Node.js and Typescript, and to simplify connecting to the MySQL database, I wanted to use TypeORM.
TypeORM is awesome. Previously, I had to create the database from scratch and I connected to the database directly and subsequently executed carefully prepared sql queries with parameters. With TypeORM I can specify entities, add columns with specific qualities.
Tag: oblivion
Posts
Turn off Oblivion head bobbing
Every now and then I like to play my beloved Oblivion. To keep things interesting I have installed quite some mods over the years. At one point, however, my head started bobbing while walking and it seemed like I was in crouching mode when standing still. The problem persisted even until after I installed all my mods. Eventually I found the culprit, but to help other possible victims, I will list possible solutions to the problem of not being able to turn off head bobbing:
Tag: php
Posts
How to mock a GuzzleHttp client that makes a request to a third-party API in a Laravel feature test?
In a Laravel project I have a feature test in which I test an internal endpoint. The endpoint has a Controller calls a method on a Service. The Service then tries to call a third-party endpoint. It is this third-party endpoint that I would like to mock.
I have looked at Guzzle’s documentation, but it seems like image/svg+xml the MockHandler strategy requires you to execute the http request inside of the test, which is not wat I want in my test.
Posts
Check if a Wordpress constant has been defined
Suppose I have configured a constant in the wp-config.php of my website:
<?php /\* Super important configuration constant \*/ define('SUPER\_IMPORTANT\_VALUE', '123e4567-e89b-12d3-a456-426614174000'); ?>Whenever you want to use this value in your website, it would be nice to know if the constant has been defined already. You’d expect to be able to do this using something like:
<?php /\* !empty does not work for a constant \*/ if (!empty(SUPER\_IMPORTANT\_VALUE)) { // Do stuff } ?
Posts
Behat: context class not found and can not be used.
If you are using Behat for testing your PHP application and you encounter the following error after trying to run your tests:
In UninitializedContextEnvironment.php line 44: Tests\\Feature\\Behat\\Context\\Account\\MyOldContext\\ context class not found and can not be used. Do not forget to remove your obsolete Behat Context file (MyOldContext in this case) from your behat.yml configuration file:
default: suites: default: paths: - '%paths.base%/tests/Feature/Behat/features' contexts: - Tests\\Feature\\Behat\\Context\\ApplicationContext # Remove the old context file - Tests\\Feature\\Behat\\Context\\MyOldContext - Tests\\Feature\\Behat\\Context\\EmailContext - Behat\\MinkExtension\\Context\\MinkContext - behatch:context:browser - behatch:context:debug - behatch:context:system - behatch:context:json - behatch:context:rest
Posts
Wordpress cannot send emails to email addresses on its own domain
Imagine the following situation: You have a Wordpress website hosted on example.com. The host has a Plesk configuration panel. Your email is handled by Google Workspace. MX records have been configured for this in Plesk, as described here image/svg+xml . The website has a contact form that should send an email to you, the owner of the website, on info@example.com.
But… the emails are not arriving.
Posts
Organize your Wordpress theme's functions.php by using namespaces and classes
As you can extend your Wordpress theme by adding actions to the theme’s functions.php, it is safe to say that it is very easy to bloat this file with hundreds of lines of code.
The nasty thing is that the usual advice is to write a function and then add that function as an action by passing the function’s name as a string. That would look something like this:
<?php // file: functions.
Posts
Easy full-width embedded Google Maps in php
Just an easy full-width embedded Google Maps snippet image/svg+xml for my own reference:
<!-- In PHP --> <iframe src=" <?php $search\_terms = rawurlencode("3 Abbey Road, London, GB NW8 9AY"); $src = "https://www.google.com/maps?q=2880%20" . $search\_terms . "&t=&z=15&ie=UTF8&iwloc=&output=embed"; echo $src; ?>" width="600" height="500" style="border:0; width: 100% !important;" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" allowfullscreen="" loading="lazy"> </iframe> <!-- Or, in raw HTML --> <iframe src="https://www.google.com/maps?q=2880%203%20Abbey%20Road%2C%20London%2C%20GB%20NW8%209AY&t=&z=15&ie=UTF8&iwloc=&output=embed" style="border: 0px none; width: 100% !
Posts
Preserve line breaks from a textarea in Wordpress
Today, I have added some customization settings to a Wordpress website. One of these settings consisted of a textarea input that would be used to enter and display an address. When I wanted to display the address, however, the address was displayed as one single line where it should have been displayed on three lines (Street + number, postal code, city).
// Incorrect code: <?php $address = get\_theme\_mod('address', ''); if ($address) { echo $address; } ?
Posts
phpMyAdmin - Error | Incorrect format parameter
If you are ever trying to import a (large) existing database through phpMyAdmin and you are getting the following error, you might want to check your php.ini file.
\# File: php.ini memory\_limit = 256M post\_max\_size = 128M upload\_max\_filesize = 128M max\_execution\_time = 600 max\_input\_time = 600 Try increasing the values image/svg+xml of the configuration variables until you get successful results.
If you are using Docker to boot up your phpMyAdmin instance, you might also want to check the UPLOAD_LIMIT environment variable in your docker-compose.
Tag: phpmyadmin
Posts
phpMyAdmin - Error | Incorrect format parameter
If you are ever trying to import a (large) existing database through phpMyAdmin and you are getting the following error, you might want to check your php.ini file.
\# File: php.ini memory\_limit = 256M post\_max\_size = 128M upload\_max\_filesize = 128M max\_execution\_time = 600 max\_input\_time = 600 Try increasing the values image/svg+xml of the configuration variables until you get successful results.
If you are using Docker to boot up your phpMyAdmin instance, you might also want to check the UPLOAD_LIMIT environment variable in your docker-compose.
Tag: phpstorm
Posts
Debug PHPUnit in Docker using PHPStorm
Problem I have a Docker setup that consists of:
A container that runs PHP A container that runs a MySQL database I am using PHPStorm for development and I would like to debug my PHPUnit tests that run inside of Docker container #1. However, when I try to do this, I get an error:
PDOException : SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo for tms-api-mysql failed: Name or service not known /var/www/html/vendor/illuminate/database/Connectors/Connector.
Tag: phpunit
Posts
Debug PHPUnit in Docker using PHPStorm
Problem I have a Docker setup that consists of:
A container that runs PHP A container that runs a MySQL database I am using PHPStorm for development and I would like to debug my PHPUnit tests that run inside of Docker container #1. However, when I try to do this, I get an error:
PDOException : SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo for tms-api-mysql failed: Name or service not known /var/www/html/vendor/illuminate/database/Connectors/Connector.
Tag: plesk
Posts
Wordpress cannot send emails to email addresses on its own domain
Imagine the following situation: You have a Wordpress website hosted on example.com. The host has a Plesk configuration panel. Your email is handled by Google Workspace. MX records have been configured for this in Plesk, as described here image/svg+xml . The website has a contact form that should send an email to you, the owner of the website, on info@example.com.
But… the emails are not arriving.
Tag: pm2
Posts
Host a static Angular build in an Azure App Service
Building an Angular app usually results in a bunch of files, mainly consisting of Javascript files, CSS files, and an index.html.
An Azure App Service normally wants to host an application using a startup command for a specific stack (PHP, Node, Python, etc.).
Technically, you could run your Angular app as a Node app. In that case you would run npm run start or ng serve as the startup command.
Tag: pods
Posts
Combine custom post types in one blog page
If you, like me, are using Pods image/svg+xml to create custom post types, you might have noticed that the post types created using Pods do not appear on your blog page by default. This is because Wordpress only queries posts with the post type post by default.
Now, you may not even want to display your pods on the blog page, but if you do, there are several ways to do this (and the choice is yours).
Tag: prettier
Posts
Format code on save using ESLint and VS Code
I have always had problems when combining Prettier image/svg+xml and ESLint image/svg+xml the same project in VS Code. Prettier would not respect my ESLint rules or vice versa. Sometimes I could mitigate the problems by using the eslint-config-prettier package in my ESLint configuration.
But now, thanks to James Quick image/svg+xml I’ve found a way to get rid of Prettier while still having the format on save feature in VS Code.
Tag: react
Posts
React modal component styled with TailwindCSS in TypeScript
This React component provides a flexible and animated modal dialog, using Tailwind CSS for styling. It’s designed to be easily integrated into any React project that already includes Tailwind CSS for its styling needs.
Features: Animations: Smooth transition for opening and closing the modal with fade and translation effects. Backdrop: Includes a clickable backdrop that closes the modal, enhancing the user experience and interaction. Accessibility: Implements focus management and can be closed with the Escape key, adhering to good accessibility practices.
Posts
React & Tailwind CSS Tooltip Component
Tooltip component export function Tooltip({ content }) { return ( {/* Tailwind's group class will be used trigger the hover */} <span className="group"> {/* Font Awesome question mark icon */} <i className="fas fa-question-circle text-black group-hover:scale-120 ml-1 cursor-pointer ease-in-out duration-300 transition-transform"></i> <span className={` w-full absolute rounded shadow text-sm font-normal font-sans bg-black text-white p-2 pointer-events-none group-hover:pointer-events-auto opacity-0 group-hover:opacity-100 left-0 -top-3 -translate-y-3/4 group-hover:-translate-y-full ease-in-out duration-300 transition-[transform,opacity]`} > {/* Set inner HTML or just output content in an expression */} <span dangerouslySetInnerHTML={{ __html: content }}></span> {/* Optional speech balloon triangle pointing down */} <div className={` absolute w-0 h-0 border-l-4 border-t-4 border-r-4 border-b-4 border-black left-1/2 -translate-x-2 -bottom-1 transform rotate-45 shadow`} ></div> </span> </span> ); } How to use Tooltip import { Tooltip } from ".
Posts
Update the PUBLIC_URL environment variable in Gitlab's CI for a React website hosted in a subfolder
When hosting a React website in a subfolder, you want the paths to the images and fonts to be updated as well. When the path of an image in your development environment is /images/background.jpg and your website is hosted at https://example.com/app, you want the path to be updated to /app/images/background.jpg in the production build.
You can do this using the PUBLIC_URL environment variable image/svg+xml .
Tag: regex
Posts
Where is Gitlab's test coverage parsing setting
Today, I wanted to set the regular expression for my test coverage results in Gitlab.
According to Gitlab’s documentation image/svg+xml , I should be able to do that in the test coverage parsing setting in my project settings, by navigating to Settings > CI/CD > General pipelines.
Problem However, I could not find the setting there. So where can I set the regular expression for the test coverage parsing setting in Gitlab?
Posts
Quickly remove unwanted IDs in JSON
I am currently duplicating entities through an API and there is no duplicate feature yet. Therefore, I am copying the JSON output of an entity and using the POST method of the API to re-create it with a different ID. In order to avoid errors, I have to delete all IDs from the JSON. To do that, I have found a regex that helps me find all the "id": "{guid}" combinations that I can then replace with an empty string using VS Code or Notepad++.
Tag: rollup
Posts
Handle imports without extensions in Vue.js 2
If you want to import your Vue components in the following way, so without a .vue or .js extension:
import CrazyComponent from '@/components/CrazyComponent'; // instead of import CrazyComponent from '@/components/CrazyComponent.vue'; There are some things you have to configure. I will outline these things below:
Rollup Add the following to your rollup.config.js:
nodeResolve({ browser: true, jsnext: true, main: true, extensions: ['.js', '.vue'] }), ESLint Add the following to your eslintrc.
Posts
Use aliases in Vue.js imports
I don’t like to do relative imports like this:
import CrazyComponent from "../../components/CrazyComponent"; Instead, I like to import my components (stores, helpers, models, etc.) like this:
import CrazyComponent from "@/components/CrazyComponent"; You might want to configure some stuff to make this possible. I will outline these configurations below:
ESLint First, install eslint-import-resolver-custom-alias:
npm install eslint-import-resolver-custom-alias --save-dev In your eslintrc.js or the eslintConfig section in your package.json, add the following resolver under "import/resolver".
Tag: seeder
Posts
Easy Node.js Mysql database table seeder
First, install npm dependencies:
npm i mysql2 @faker-js/faker dotenv Run the script with the command
node ./index.js Don’t forget to add the mysql db credentials to your .env file and of course edit the getSeedQuery function if you want to use it for your own table.
const mysql = require("mysql2"); const { faker } = require("@faker-js/faker"); require("dotenv").config(); function getSeedQuery(amount = 10000) { return Array.from({ length: amount }) .map(() => { const date = faker.
Tag: skeleton
Posts
A very simple animated skeleton gist
Just for my own reference, I will publish the skeleton css gist image/svg+xml I use in many of my projects here. It is very easy to use and very easy to extend with new shapes. You can check the --card and --rounded modifiers image/svg+xml for inspiration.
In Sass:
.skeleton { display: inline-block; height: 1em; position: relative; overflow: hidden; background-color: #dddbdd; &::after { position: absolute; top: 0; right: 0; bottom: 0; left: 0; transform: translateX(-100%); background-image: linear-gradient( 90deg, rgba(#fff, 0) 0, rgba(#fff, 0.
Posts
Angular :host in css
So I was working on creating a nice extendable skeleton image/svg+xml component when I stumbled upon a problem: I wanted to create a base skeleton style for the component that could be extended outside the component using utility classes. Something like this:
// Skeleton template <div class="skeleton"></div> // Skeleton CSS .skeleton { background: lightgray; width: 100%; height: 1em; // etc. } // Implementation of skeleton component // with utility classes <app-skeleton class="rounded p-1"></app-skeleton> However, what happened during runtime was the following:
Tag: sourcemaps
Posts
Prevent your blob storage from storing too many blobs
I host my Angular websites using Azure and I use Application Insights to find and report errors. Normally, the exception gets logged, but Angular builds usually have minified javascript, making it hard to debug the origin of an error.
Luckily, Azure support uploading the sourcemaps of a minified Javascript bundle to a Azure Blob Storage Container, which can then be used by Azure’s Application Insights to un-minify the stack trace of an error.
Tag: sql
Posts
SQL error with code 40531 when trying to fetch schema in Azure Database Sync
As I was trying to sync my Hub database to my Member database in Azure Database Sync, I got this error when trying to fetch the schema of the Hub database:
Getting schema information for the database failed with the exception "Failed to connect to server databasename-0182730712073.database.windows.net.Inner exception: SqlException ID: {someGuid}, Error Code: -2146232060 - SqlError Number:40531, Message: SQL error with code 40531 For more information, provide tracing ID ‘{someGuid}’ to customer support.
Posts
Test multiple SQL Server connection strings in a dotnet console app
As I have explained how to create some new logins and users in my previous post image/svg+xml , I now had to create some connection strings for those logins. To check if all logins were created successfully, I have created a small dotnet console application to test out the connection strings associated with these logins:
using System.Data.SqlClient; class Credentials { public string Username { get; set; } public string Password { get; set; } public string Server { get; set; } public Credentials(string username, string password, string server = "sql-server.
Posts
Create an Azure SQL Server login and connect a user to it
In my previous post image/svg+xml I showed how you can convert a .bak file to a DAC file and how to fix any errors that may appear. For the same job, I had to add some new SQL logins and users after the migration of the database. This post serves as a notebook for how to do that.
\-- Execute this query in the "master" database -- Create new login CREATE LOGIN \[new-login\] WITH PASSWORD = 'complex-password' GO -- Execute these queries in the target database -- Create a user and connect it to the login CREATE USER \[new-user\] FOR LOGIN \[new-login\] -- Create a role to execute stored procedures CREATE ROLE \[db\_executor\] AUTHORIZATION \[dbo\] GO GRANT EXECUTE TO \[db\_executor\] GO -- Give the user read/write/execute rights sp\_addrolemember @rolename = 'tc\_execute', @membername = 'new-user' GO sp\_addrolemember @rolename = 'db\_datareader', @membername = 'new-user' GO sp\_addrolemember @rolename = 'db\_datawriter', @membername = 'new-user' GO -- Check if roles have been assigned to the user correctly SELECT UserType='Role', DatabaseUserName = '{Role Members}', LoginName = DP2.
Posts
Fix a SQL database before exporting to a DAC .bacpac file
When you want to migrate an old (on-premise) SQL database to an Azure SQL database, you need to export the database to a DAC .bacpac file. Such an export also includes schemas, views and users/logins. It is easy to receive errors when attempting to make a .bacpac export. In this post, I sum up the errors I received and a way to fix them.
1. Drop Windows users In my case, the database that I wanted to migrate contained references to Windows users.
Tag: static
Posts
Host a static Angular build in an Azure App Service
Building an Angular app usually results in a bunch of files, mainly consisting of Javascript files, CSS files, and an index.html.
An Azure App Service normally wants to host an application using a startup command for a specific stack (PHP, Node, Python, etc.).
Technically, you could run your Angular app as a Node app. In that case you would run npm run start or ng serve as the startup command.
Tag: symlinks
Posts
How to keep Flywheel Local and your repository separated using symlinks
Since a while, I have been using Flywheel’s Local for my local WordPress development server and it has been. No time spend on configuration Docker, Apache, database connections, et cetera.
However, one thing that has been bugging me is the question of how to combine Local’s configuration and my own code, which contains my WordPress themes and plugins. As Local creates its own WordPress folders (wp-content etc.) inside its configuration folders, how should I approach such a situation?
Tag: tailwindcss
Posts
React modal component styled with TailwindCSS in TypeScript
This React component provides a flexible and animated modal dialog, using Tailwind CSS for styling. It’s designed to be easily integrated into any React project that already includes Tailwind CSS for its styling needs.
Features: Animations: Smooth transition for opening and closing the modal with fade and translation effects. Backdrop: Includes a clickable backdrop that closes the modal, enhancing the user experience and interaction. Accessibility: Implements focus management and can be closed with the Escape key, adhering to good accessibility practices.
Posts
Masonry using TailwindCSS
This code snippet demonstrates a simple yet effective way to create a masonry layout using TailwindCSS. Utilizing the columns-3 class, it organizes content into three neat columns, ideal for various types of content. The gap-3 class adds horizontal spacing between these columns, while mb-3 on each block ensures vertical spacing, maintaining a clean and organized look.
<div class="h-screen w-full bg-slate-300 p-5"> <div class="p-5 columns-3 gap-3 bg-white rounded-lg drop-shadow-lg"> <div class="mb-3 bg-amber-600 text-white text-center p-3 rounded"> Lorem ipsum </div> <div class="mb-3 bg-amber-600 text-white text-center p-3 rounded"> Lorem ipsum, hello world!
Posts
Fade out text using a gradient and Tailwind CSS
In many cases, we have reasons not to display the whole text of an article or page and we just want to show an excerpt. Sometimes we break off the text using ellipsis. But sometimes we might want to fade out the text image/svg+xml . And sometimes we want to do that in Tailwind CSS. Is that possible? Yes it is.
Tailwind CSS example <div class="mt-24 w-96 p-4 mx-auto rounded-lg shadow-lg overflow-hidden relative after:content-[''] after:absolute after:inset-x-0 after:bottom-0 after:h-16 after:bg-gradient-to-b after:from-transparent after:to-white"> <h1 class="text-3xl mb-3 font-bold underline"> Hello world!
Posts
Use Wordpress’ paginate_link function with custom html and tailwindcss
Wordpress’ paginate_link function image/svg+xml is pretty neat for generating pagination links without any hassle. It does not, however, give you easy control over the exact html output. This makes it hard for styling the list, list items and links when using tailwindcss as we cannot add the utility classes to the elements.
To make this easier, I wrote a little procedure that will do some string replacements that allows us to have more control over the classes that we want to use.
Posts
React & Tailwind CSS Tooltip Component
Tooltip component export function Tooltip({ content }) { return ( {/* Tailwind's group class will be used trigger the hover */} <span className="group"> {/* Font Awesome question mark icon */} <i className="fas fa-question-circle text-black group-hover:scale-120 ml-1 cursor-pointer ease-in-out duration-300 transition-transform"></i> <span className={` w-full absolute rounded shadow text-sm font-normal font-sans bg-black text-white p-2 pointer-events-none group-hover:pointer-events-auto opacity-0 group-hover:opacity-100 left-0 -top-3 -translate-y-3/4 group-hover:-translate-y-full ease-in-out duration-300 transition-[transform,opacity]`} > {/* Set inner HTML or just output content in an expression */} <span dangerouslySetInnerHTML={{ __html: content }}></span> {/* Optional speech balloon triangle pointing down */} <div className={` absolute w-0 h-0 border-l-4 border-t-4 border-r-4 border-b-4 border-black left-1/2 -translate-x-2 -bottom-1 transform rotate-45 shadow`} ></div> </span> </span> ); } How to use Tooltip import { Tooltip } from ".
Posts
Use a fallback for Safari’s problematic mix-blend-mode implementation, in TailwindCSS
Recently I had been working on a website that uses mix-blend-mode: color. I just found out it didn’t work on Safari. Apparently color is not supported image/svg+xml . I had to find a way to maintain this mix blend mode for non-Safari browsers, in which it worked fine, but override it in Safari.
Then I found this overly verbose answer image/svg+xml on Stackoverflow.
Posts
Prevent a flex button to take up full width
Regular html & css <style> .container { display: flex; flex-direction: column; } .item { display: flex; flex-direction: row; align-items: center; align-self: center; } </style> <body> <div class="container"> <button class="item"> <span>Click me!</span> <i>Icon</i> </button> </div> </body> Or with TailwindCSS <body> <div class="flex flex-col"> <button class="flex flex-row items-center self-center"> <span>Click me!</span> <i>Icon</i> </button> </div> </body> See also https://stackoverflow.com/a/67819933/4496102 image/svg+xml
Posts
How to combine Webpack, Tailwindcss & Wordpress using webpack-watch-files-plugin
For my client I am currently building a website that makes use of tailwindcss image/svg+xml , a utility-first image/svg+xml CSS framework. With utility classes you can directly style elements using classes such as text-center (center the text) or bg-red-600 (red background, shade 600). Tailwindcss contains a lot of those classes and also allows combining breakpoints with these classes, such as md:font-bold (make font bold on medium sized devices or larger).
Tag: terminal
Posts
Simple GPT CLI
Using my friend ChatGPT I made a little CLI to talk to… GPT. It’s basically a bash script that you can place in one of you bin folders and execute from wherever in your terminal:
gpt "I need a new cactus, what is a nice type that needs little maintenance?" After which GPT will answer you with (hopefully) a nice answer:
GPT-3 answers: One type of cactus that is low-maintenance is the Peruvian apple cactus.
Posts
Unable to find the selected font "NovaMono for Powerline".
On one of my computers I use Windows Terminal with Git Bash and PowerShell as my default terminals. For these terminals I have customized the appearance in Windows Terminal, which is a pretty nice feature. For both terminals, I had configured the NovaMono for Powerline font, which I had previously installed to Windows.
On a certain day I suddenly started getting these messages while either one of the terminals was initializing:
Posts
Repository of convenient terminal commands
This article will be filled with convenient terminal commands for my own reference.
Logs Check latest logs in linux Navigation journalctl -xe Go back to previous location cd - Other List all services service --status-all Permissions Show read / write permissions as numbers find . -maxdepth 1 -printf "%m %f\\n" Services See under which user a service is running ps -ef
Tag: testing
Posts
How to mock a GuzzleHttp client that makes a request to a third-party API in a Laravel feature test?
In a Laravel project I have a feature test in which I test an internal endpoint. The endpoint has a Controller calls a method on a Service. The Service then tries to call a third-party endpoint. It is this third-party endpoint that I would like to mock.
I have looked at Guzzle’s documentation, but it seems like image/svg+xml the MockHandler strategy requires you to execute the http request inside of the test, which is not wat I want in my test.
Tag: twenty-thirteen
Posts
Copy and modify the custom header of a Wordpress parent theme to a child theme
For a client I am currently creating a new website in Wordpress. To speed up design, I am basing my own Wordpress theme on an existing theme: Twenty Thirteen image/svg+xml . It is fairly old already (2013), but I like the general layout with a header and navigation on top.
Whenever you upload a header image in this theme, the image would be displayed over the full width of the page.
Tag: typeorm
Posts
SyntaxError: Cannot use import statement outside a module
For the secret game I am developing, I needed a database to store User and Profile data. The game’s backend server is developed using Node.js and Typescript, and to simplify connecting to the MySQL database, I wanted to use TypeORM.
TypeORM is awesome. Previously, I had to create the database from scratch and I connected to the database directly and subsequently executed carefully prepared sql queries with parameters. With TypeORM I can specify entities, add columns with specific qualities.
Tag: typescript
Posts
Throw error on missing environment variables in Next.js
Since this year I have been working on a new project for our client. A Next.js project for the first time in years. This morning I was having some problems as the Next.js website tried to fetch data from the API but receiving errors instead. A query variable in the URL was set to "undefined". After some poking around, I found out it was due to a missing environment variable in the project’s .
Posts
Square loading favicon in Typescript
Based on rpsthecoder’s square loading favicon image/svg+xml in JavaScript, but now in proper Typescript.
/** * Square loading favicon in Typescript * Author: Drikus Roor * Original author: https://github.com/rpsthecoder/square-loading-favicon */ interface IFavicon extends Element { href: string; } export function animateFavicon() { const canvas = document.querySelector("canvas"); if (!canvas) { return; } const context = canvas.getContext("2d"); if (context) { const favicon = document.
Posts
Typescript module resolution for test files in VS Code
In a Typescript project I am working on, I use tsconfig’s paths property to create local modules that I can refer to in the project’s import without having to type a long relative directory.
E.g. Instead of typing:
import { module } from '../../../modules/module'; I want to type:
import { module } from '@modules/module'; To accomplish this, I have added the paths property to my root-level tsconfig.json file:
// Root-level tsconfig // File: .
Posts
SyntaxError: Cannot use import statement outside a module
For the secret game I am developing, I needed a database to store User and Profile data. The game’s backend server is developed using Node.js and Typescript, and to simplify connecting to the MySQL database, I wanted to use TypeORM.
TypeORM is awesome. Previously, I had to create the database from scratch and I connected to the database directly and subsequently executed carefully prepared sql queries with parameters. With TypeORM I can specify entities, add columns with specific qualities.
Tag: upptime
Posts
How to add a search bar to an Upptime status page
Upptime image/svg+xml is a very neat tool that allows you to track the status of your websites and creates Github issues whenever a site has downtime. The extra neat aspect of Upptime is that it works entirely on Github. No hosting or cloud provider is necessary whatsoever, it all runs using Github Actions and Github Pages.
Upptime is not perfect (yet) though. It misses some features that would make it perfect for me.
Tag: vs-code
Posts
Typescript module resolution for test files in VS Code
In a Typescript project I am working on, I use tsconfig’s paths property to create local modules that I can refer to in the project’s import without having to type a long relative directory.
E.g. Instead of typing:
import { module } from '../../../modules/module'; I want to type:
import { module } from '@modules/module'; To accomplish this, I have added the paths property to my root-level tsconfig.json file:
// Root-level tsconfig // File: .
Tag: vscode
Posts
Format code on save using ESLint and VS Code
I have always had problems when combining Prettier image/svg+xml and ESLint image/svg+xml the same project in VS Code. Prettier would not respect my ESLint rules or vice versa. Sometimes I could mitigate the problems by using the eslint-config-prettier package in my ESLint configuration.
But now, thanks to James Quick image/svg+xml I’ve found a way to get rid of Prettier while still having the format on save feature in VS Code.
Tag: vue
Posts
Test vue component event emits
const WrapperComponent = { components: { ChildComponent, }, methods: { onUpdate: jest.fn(), }, template: '<child-component @onUpdate="onUpdate" />', }; describe('ChildComponent', () => { let wrapper; beforeEach(() => { wrapper = mount(WrapperComponent, {}); }); afterEach(() => { wrapper.destroy(); }); it('emits onUpdate event', async () => { const spy = jest.spyOn(WrapperComponent.methods, 'onUpdate'); // do something that would make child component emit the 'onUpdate' event expect(spy).toHaveBeenCalled(); }); });
Tag: vue-js
Posts
Handle imports without extensions in Vue.js 2
If you want to import your Vue components in the following way, so without a .vue or .js extension:
import CrazyComponent from '@/components/CrazyComponent'; // instead of import CrazyComponent from '@/components/CrazyComponent.vue'; There are some things you have to configure. I will outline these things below:
Rollup Add the following to your rollup.config.js:
nodeResolve({ browser: true, jsnext: true, main: true, extensions: ['.js', '.vue'] }), ESLint Add the following to your eslintrc.
Posts
Use aliases in Vue.js imports
I don’t like to do relative imports like this:
import CrazyComponent from "../../components/CrazyComponent"; Instead, I like to import my components (stores, helpers, models, etc.) like this:
import CrazyComponent from "@/components/CrazyComponent"; You might want to configure some stuff to make this possible. I will outline these configurations below:
ESLint First, install eslint-import-resolver-custom-alias:
npm install eslint-import-resolver-custom-alias --save-dev In your eslintrc.js or the eslintConfig section in your package.json, add the following resolver under "import/resolver".
Posts
Vue.js with dark mode while taking system preference and user preference into account
tl;dr - A vue.js example of adding dark mode support to your website that takes system preference and user preference into account. See link image/svg+xml for source.
When you are developing a website with dark-mode support, there are usually two paths you can take:
Use the [prefers-color-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme) CSS media feature and thereby use the system preference. Use a website setting to set a .
Tag: webp
Posts
Sorry, this file type is not permitted for security reasons.
Today, I wanted to upload a WebP image/svg+xml image to a Wordpress website, because we all know WebP is the superior image format image/svg+xml nowadays.
Unfortunately, Wordpress currently (I am using 5.7.2) does not support it. Wordpress 5.8, however, is said to support WebP.
At the moment of writing, Wordpress 5.8 has not been released yet. So, if you cannot wait until the release of Wordpress 5.
Tag: webpack
Posts
Use aliases in Vue.js imports
I don’t like to do relative imports like this:
import CrazyComponent from "../../components/CrazyComponent"; Instead, I like to import my components (stores, helpers, models, etc.) like this:
import CrazyComponent from "@/components/CrazyComponent"; You might want to configure some stuff to make this possible. I will outline these configurations below:
ESLint First, install eslint-import-resolver-custom-alias:
npm install eslint-import-resolver-custom-alias --save-dev In your eslintrc.js or the eslintConfig section in your package.json, add the following resolver under "import/resolver".
Posts
How to combine Webpack, Tailwindcss & Wordpress using webpack-watch-files-plugin
For my client I am currently building a website that makes use of tailwindcss image/svg+xml , a utility-first image/svg+xml CSS framework. With utility classes you can directly style elements using classes such as text-center (center the text) or bg-red-600 (red background, shade 600). Tailwindcss contains a lot of those classes and also allows combining breakpoints with these classes, such as md:font-bold (make font bold on medium sized devices or larger).
Posts
Relative path font import issues in Webpack 5
This is mainly a note to myself that I can use as a reference when a future me is making the same mistake again.
As I am creating the Wordpress theme for this website, I ran into some issues when trying to import the font that is currently used in the website’s title heading.
My folder structure is as follows:
src - css - fonts dist - css - fonts And I import my font like this:
Tag: windows
Posts
Unable to find the selected font "NovaMono for Powerline".
On one of my computers I use Windows Terminal with Git Bash and PowerShell as my default terminals. For these terminals I have customized the appearance in Windows Terminal, which is a pretty nice feature. For both terminals, I had configured the NovaMono for Powerline font, which I had previously installed to Windows.
On a certain day I suddenly started getting these messages while either one of the terminals was initializing:
Posts
How to move an off-screen application window in Windows 11
As I frequently disconnect and connect monitors from and to my laptop, a bug(?) in Windows 11 causes the windows of application to disappear sometimes. This usually happens with [Zettlr](https://www.zettlr.com/), my note-taking app of choice. This frustrated me endlessly, as I want my notes to be easily accessible. But now I think I found a solution to make the window appear again.
Simply press alt + space whenever the disappeared window is active.
Tag: wordpress
Posts
How to Display Custom Field Values in Wordpress Admin for Custom Post Types
Problem: Custom fields not visible in admin overview Have you ever struggled with the lack of visibility of custom fields in your WordPress admin dashboard, especially when working with custom post types? It can be challenging to quickly view the specific metadata associated with these posts. This is a common issue for WordPress developers and content managers who need a streamlined way to manage and display custom data. The good news is that with a bit of code, you can easily add custom columns to your admin dashboard to display these values.
Posts
Highlight search terms in Wordpress
To highlight search terms in the content in your Wordpress search result page, add the following function to your functions.php file:
function search_excerpt_highlight() { $content = get_the_content(); $content = wp_strip_all_tags($content); // Set the excerpt length $excerpt_length = 100; // You can adjust this value to your desired excerpt length $padding = 10; // Add padding around the search term $keys = explode(' ', get_search_query()); $first_key = $keys[0]; // Find the first occurrence of the search term $term_pos = stripos($content, $first_key); if ($term_pos !
Posts
Use Wordpress’ paginate_link function with custom html and tailwindcss
Wordpress’ paginate_link function image/svg+xml is pretty neat for generating pagination links without any hassle. It does not, however, give you easy control over the exact html output. This makes it hard for styling the list, list items and links when using tailwindcss as we cannot add the utility classes to the elements.
To make this easier, I wrote a little procedure that will do some string replacements that allows us to have more control over the classes that we want to use.
Posts
Wordpress custom blocks: Pass down attributes to child blocks
Suppose you are working on a set of interacting custom blocks in Wordpress. You have a child block that needs information from the parent block to display, in this situation, information about a specific record. In such a case you want to use Block context image/svg+xml .
Block context is a feature which enables ancestor blocks to provide values which can be consumed by descendent blocks within its own hierarchy.
Posts
Add JavaScript to a custom block in Wordpress
Using Wordpress custom blocks, I’m currently trying to create a popover component that contains a button and a hidden content. The hidden content should appear when the user clicks on or hovers over the button (on the frontend of the website, not in the block editor).
Problem However, when I add an onClick or onHover to the button, the event handler is not executed.
Additionally, trying to use the useState hook to store the display state of the popover crashes my block editor.
Posts
Check if a Wordpress constant has been defined
Suppose I have configured a constant in the wp-config.php of my website:
<?php /\* Super important configuration constant \*/ define('SUPER\_IMPORTANT\_VALUE', '123e4567-e89b-12d3-a456-426614174000'); ?>Whenever you want to use this value in your website, it would be nice to know if the constant has been defined already. You’d expect to be able to do this using something like:
<?php /\* !empty does not work for a constant \*/ if (!empty(SUPER\_IMPORTANT\_VALUE)) { // Do stuff } ?
Posts
Insert a Google Analytics sitetag in Wordpress using a constant defined in wp-config.php
First, define your Google Analytics constant in wp-config.php:
// wp-config.php /\* Google Analytics Key \*/ define('GOOGLE\_ANALYTICS\_KEY', 'G-XXXXXXXXXX'); Then, insert the following gist inside the <head> of your website (header.php in my case):
// header.php (for example) <?php if (defined('GOOGLE\_ANALYTICS\_KEY')) { ?><!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo GOOGLE\_ANALYTICS\_KEY; ?>"></script> <script> window.dataLayer = window.dataLayer || \[\]; function gtag() { dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', '<?
Posts
Wordpress cannot send emails to email addresses on its own domain
Imagine the following situation: You have a Wordpress website hosted on example.com. The host has a Plesk configuration panel. Your email is handled by Google Workspace. MX records have been configured for this in Plesk, as described here image/svg+xml . The website has a contact form that should send an email to you, the owner of the website, on info@example.com.
But… the emails are not arriving.
Posts
How to quickly add multiple colors to your Wordpress theme customizer
I am currently working on dark mode support for a Wordpress theme. For that, the website will need to use different colors depending on the preference of the user. At the same time, I want those colors to be easily customizable through Wordpress' Customizer.
What I don’t want, however, is 500 lines of code just to add a few colors. The hooks for adding Wordpress customizer settings image/svg+xml and controls image/svg+xml are no one-liners.
Posts
Organize your Wordpress theme's functions.php by using namespaces and classes
As you can extend your Wordpress theme by adding actions to the theme’s functions.php, it is safe to say that it is very easy to bloat this file with hundreds of lines of code.
The nasty thing is that the usual advice is to write a function and then add that function as an action by passing the function’s name as a string. That would look something like this:
<?php // file: functions.
Posts
Preserve line breaks from a textarea in Wordpress
Today, I have added some customization settings to a Wordpress website. One of these settings consisted of a textarea input that would be used to enter and display an address. When I wanted to display the address, however, the address was displayed as one single line where it should have been displayed on three lines (Street + number, postal code, city).
// Incorrect code: <?php $address = get\_theme\_mod('address', ''); if ($address) { echo $address; } ?
Posts
How to keep Flywheel Local and your repository separated using symlinks
Since a while, I have been using Flywheel’s Local for my local WordPress development server and it has been. No time spend on configuration Docker, Apache, database connections, et cetera.
However, one thing that has been bugging me is the question of how to combine Local’s configuration and my own code, which contains my WordPress themes and plugins. As Local creates its own WordPress folders (wp-content etc.) inside its configuration folders, how should I approach such a situation?
Posts
Force HTTPS on your WordPress website
You have finally installed that SSL certificate to your website and now the website keeps hanging in an unsafe http connection. What is up with that?
To force a HTTPS connection, we only have to add some lines to the .htaccess file, which is located in the root of the public html folder of your WordPress website:
.htaccess is located in the public html folder of your WordPress website, which is the same folder that contains the wp-admin, wp-content, and wp-includes folder.
Posts
Add and display a setting to your Wordpress child theme
My client asked me to show a short message above every page and post and wished to be able to modify this text himself through the theme customizer.
Now, this is not too hard and I have done it multiple times before, but I keep forgetting the specifics. This post is therefore meant as a quick cheatsheet for myself, but maybe it will help you, anonymous internet user, as well.
Posts
Combine custom post types in one blog page
If you, like me, are using Pods image/svg+xml to create custom post types, you might have noticed that the post types created using Pods do not appear on your blog page by default. This is because Wordpress only queries posts with the post type post by default.
Now, you may not even want to display your pods on the blog page, but if you do, there are several ways to do this (and the choice is yours).
Posts
Sorry, this file type is not permitted for security reasons.
Today, I wanted to upload a WebP image/svg+xml image to a Wordpress website, because we all know WebP is the superior image format image/svg+xml nowadays.
Unfortunately, Wordpress currently (I am using 5.7.2) does not support it. Wordpress 5.8, however, is said to support WebP.
At the moment of writing, Wordpress 5.8 has not been released yet. So, if you cannot wait until the release of Wordpress 5.
Posts
How to combine Webpack, Tailwindcss & Wordpress using webpack-watch-files-plugin
For my client I am currently building a website that makes use of tailwindcss image/svg+xml , a utility-first image/svg+xml CSS framework. With utility classes you can directly style elements using classes such as text-center (center the text) or bg-red-600 (red background, shade 600). Tailwindcss contains a lot of those classes and also allows combining breakpoints with these classes, such as md:font-bold (make font bold on medium sized devices or larger).
Posts
Copy and modify the custom header of a Wordpress parent theme to a child theme
For a client I am currently creating a new website in Wordpress. To speed up design, I am basing my own Wordpress theme on an existing theme: Twenty Thirteen image/svg+xml . It is fairly old already (2013), but I like the general layout with a header and navigation on top.
Whenever you upload a header image in this theme, the image would be displayed over the full width of the page.