Snippets
Collection of my code snippets
Tags:
ios xcode simulator dark mode
02-05-22
%Recently I was testing an IOS app on my wifes phone. The UI was completly broken. Turns out she had dark mode enabled. That led me down the path of adding dark mode support to the app. Which is testable via the Xcode simulator if you know how to enable it.
Command + Shift + A: Toggles dark mode
source: https://www.kindacode.com/article/how-to-toggle-dark-mode-on-ios-simulator/
- [ xcode]
bash extract file name
17-03-22
%Comparing the following shows how to use basename to extract just the file name from a full path.
$ for file in ./content/**/*.md ; do echo $file ; done | head -10
./content/_index.de.md
./content/_index.en.md
./content/_index.ru.md
./content/blog/_index.de.md
./content/blog/_index.en.md
./content/blog/ahrn-valley/index.en.md
./content/blog/archiving-corona-cal/index.en.md
./content/blog/arco/index.de.md
./content/blog/arco/index.en.md
./content/blog/armycookbot/index.de.md
$ for file in ./content/**/*.md ; do file=$(basename $file) && echo $file ; done
_index.de.md
_index.en.md
_index.ru.md
_index.de.md
_index.en.md
index.en.md
index.en.md
index.de.md
index.en.md
index.de.md
s3 move folder / rename folder
17-03-22
%Working on my Oblastle game today. In an effort to standardize the way I store images for the game in S3 I needed to move all the files with key image-service/images/oblastle/flags/ to /image-service/images/oblastle/flag/.
Here is how I did it:
$ aws s3 mv s3://travisshears.images/image-service/images/oblastle/flags/ s3://travisshears.images/image-service/images/oblastle/flag/ --recursive --profile personal
s3 copy recursive
03-03-22
%Where were you --recursive when I was hacking around with for file * ; do aws s3 cp $file.....
$ aws s3 cp ./ s3://travisshears.images/image-service/images/oblastle/context/ --profile personal --recursive
upload: ./us-ak.jpg to s3://travisshears.images/image-service/images/oblastle/context/us-ak.jpg
upload: ./us-co.jpg to s3://travisshears.images/image-service/images/oblastle/context/us-co.jpg
upload: ./us-ar.jpg to s3://travisshears.images/image-service/images/oblastle/context/us-ar.jpg
upload: ./us-ca.jpg to s3://travisshears.images/image-service/images/oblastle/context/us-ca.jpg
upload: ./us-al.jpg to s3://travisshears.images/image-service/images/oblastle/context/us-al.jpg
upload: ./us-ct.jpg to s3://travisshears.images/image-service/images/oblastle/context/us-ct.jpg
...
--recursive is an easy win to upload a bunch of files to s3.
imagemagik .png to .jpg with white background
03-03-22
%Working on some .png map files today. I needed to covert them to small .jpg's for uses in Oblastle. Problem being by default the transparent part fills into to black. Here is how to make it white:
$ ls
us-ak.png
us-al.png
us-ar.png
us-az.png
us-ca.png
$ for file in *.png ; do magick mogrify -format jpg -resize '500' -background white -flatten $file; done
$ ls
us-ak.png
us-ak.jpg
us-al.png
us-al.jpg
us-ar.png
us-ar.jpg
us-az.png
us-az.jpg
us-ca.png
$ rm ./*.png
The important bit being -background white -flatten.
- [ imagemagik]
lower case string
13-02-22
%TR is a Unix until to translate characters I recently learned about as part of this awk snippet.
$ echo "TRAVIS" | tr '[:upper:]' '[:lower:]'
travis
- [ tr]
awk last column
13-02-22
%My first awk snippet! Today I needed to get all the file extensions in directory for a blog post I'm writing.
I solved it with:
$ fd . --type f | awk -F"." '{print $(NF)}' | tr '[:upper:]' '[:lower:]' | sort | uniq | pbcopy
Break down
fd . --type f, lists all the files in a directory recursively.
awk -F"." '{print $(NF)}', the -F"." tells awk to split columns on ".". The '{print $(NF)'} tells awk to print the last column. Normally you do something like '{print $2}' to print the second column.
tr '[:upper:]' '[:lower:]', tr is a Unix until to translate characters. In this case all upper case letters will be translated to lower case. I've created a seprate snippet for it as well.
sort | uniq, a classic combo sorts the results then gets rid of duplicates.
pbcopy, anther common one for me pipes the result into the clipboard.
- [ awk]
close the garden
24-01-22
%Started playing with garden cli today. After playing around with the local kubernetes deployments I found it annoying it left some system containers running when I was finished. To get rid of these run the following from the project directory (the dir with project.garden.yml)
$ garden delete env
$ garden plugins local-kubernetes uninstall-garden-services
- [ garden-cli]
remove brew packages
18-01-22
%Trying to clean up my laptop a bit today by removing some unused brew packages.
Normally I would use brew list
but this also list packages that are dependicies.
Here is a way to list the top level packages:
$ brew leaves
asciinema
aspell
autoconf
awscli
bat
bumpversion
...
$ brew uninstall neomutt newsboat travisshears/tap/deploy_tool weechat
...
- [ brew]
wipe git commit times
14-01-22
%Some time you don't want everyone to know exactly when you committed. This command will wipe the time stamps and set them all to today at 0:00h.
git filter-branch --env-filter '
GIT_AUTHOR_DATE="$(date +%Y-%m-%d) 00:00:00+0000"
GIT_COMMITTER_DATE="$(date +%Y-%m-%d) 00:00:00+0000"
' -- --all
It works best on fresh repos just be for pushing to remote for the first timee.
- [ git]
re export
05-01-22
%Today when writing a React hook I imported an enum type from another section of code. This enum was used as an argument to the hook. Any components that used this hook would also need to import that type enum. So just to use the hook at a minimum the component would need to import two things, the hook itself, and the type enum. To many imports cluttering stuff us!
import useCoolHook from 'Client/hooks/CoolHoook';
import HatStyleEnum from 'Client/hats/styles';
...
cool = useCoolHook(HatStyleEnum.cowboy);
What I found is the ability to re-export the type from the hook to keep the enum bundled with the hook and more easily accessible.
export {HatStyleEnum} from 'Client/hats/styles';
export const useCoolHook = (hatId: HatStyleEnum) => {
...
This way the components only have to have one import, saving space.
import useCoolHook, {HatStyleEnum} from 'Client/hooks/CoolHoook';
Also see similar snippet for js
source: stackoverflow
- [ typescript]
destructuring an array in javascript
29-11-21
%How I use to destructure Arrays:
const nums = [1,2,3];
const [a, _, c];
(a === 1) // true
(c === 3) // true
Problem is this _ is not needed and will cause problems with some ESLint setups. For example they might not allow unused variables. Turnes out you can just leave that spot blank!
const nums = [1,2,3];
const [a, , c];
(a === 1) // true
(c === 3) // true
- [ js]
emacs replace across multiple files
28-11-21
%This week I was making some changes to a hugo shortcode I use on my personal site for videos.
Old one:
{< video-with-caption
remote_url="https://travisshears.com/image-service/videos/galtenberg-ski-tour/over_the_tree.webm"
backup_url="https://travisshears.com/image-service/videos/galtenberg-ski-tour/over_the_tree.mp4"
title="through the woods we go"
>}
New one:
{< video-with-caption
webm_url="https://travisshears.com/image-service/videos/galtenberg-ski-tour/over_the_tree.webm"
mp4_url="https://travisshears.com/image-service/videos/galtenberg-ski-tour/over_the_tree.mp4"
title="through the woods we go"
>}
Problem is this change crosses 50+ files. I knew some ways with sed to regex
substitute it across the files but I wanted something more emacs. Eventually
found wgrep! Its allows you to search
with normal +default/search-project
then edit the results.
- <SPC s p> to search the project
- type search ex: "remote_url"
- <C-c C-o> to open the results
- delete some results with <d>
- <C-c C-p> to make the results editable
- make edits example :%s/remote_url/webm_url/g
- <Z Z> to save changes across all the files
- lastly review changes via git
{{< video-with-caption webm_url="https://travisshears.com/image-service/videos/emacs-replace-across-multiple-files/emacs_mass_edit_small.webm" mp4_url="https://travisshears.com/image-service/videos/emacs-replace-across-multiple-files/emacs_mass_edit_small.mp4"
}}
final patch: https://git.sr.ht/~travisshears/travisshears.com/commit/71e9c89c32f9b9f362e8e94ca8530530c1418284
In the making of this snippet I had some other fun:
- this screen recording led me to finding keycastr. A very helpful mac osx program that displays keys as you type them. Great for tutorials.
- My personal site is not open source because I write lot of drafts that don't get published for months... For this snippet I wanted to show part of that source code as a patch, decided on hosting it as a sourcehut paste. To create the paste I wrote a sourcehut-paste.
- Video was created with Quicktime screen recording feature plus my video helper app, ts-video
- [ emacs]
vs code tasks
12-11-21
%For the past years whenever I needed to lint or test a single file I would:
- right click it in the navigation tree
- copy relative path
- open the built in terminal with Command-J
- Control-R to search recent commands for 'npm run test' or 'npm run lint'
- Select old path in the command and paste with path I want to test
- hit Enter
- wait
Over time doing this adds up. Recently I stumbled upon VS Code Tasks and found a way to speed things up. By configuring the following tasks.json:
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "test single xxxxx file",
"command": "npm run test -- ${file} --coverage=false",
"problemMatcher": []
},
{
"type": "shell",
"label": "lint and fix single file xxxxx file",
"command": "./node_modules/.bin/eslint ${file} --fix",
"problemMatcher": []
},
]
}
Now to test the file that I'm currently working on I:
- Command-Shift-P to bring up commands input
- Usually 'Tasks: Run Task' is the last run command so just press Enter, In the case it is not typing 'Task' is enough to bring it up
- Then the lint and test tasks appier in the drop down and all I have to do is hit Enter again
- wait
- profit
Don't know why I held out on customizing VS Code so long! Wonder what other time saving features there are?
source: vs code docs
- [ vscode]
emacs mac umlauts
05-11-21
%Recently I've been writing a lot for the German side of my personal site. When typing in German I perfer to use the English QWERTY keyboard and just alt-u-u to type "ΓΌ". The problem I was having was emacs would intercept this and execute the capitalize-word function π. After some digging into my configs, ~/.doom.d/config.el, I was able to unset M-u only problem is it still didn't activate the mac system umlaut feature.
(global-unset-key (kbd "M-u"))
Finally after some more digging I found:
(setq ns-alternate-modifier 'none
ns-right-alternate-modifier 'meta)
It works by un-assigning the left alt to meta, allowing the system keyboard feature to kick in.
source: https://emacs.stackexchange.com/questions/61019/umlauts-in-emacs-on-mac
- [ emacs]
update a local zef module
20-10-21
%Lately I've been working locally with raku/zef modules for my CLI apps. I install them with:
$ zef install .
Turns out you can update a package very similarity. Just bump the version in the META6.json and run the same command again.
$ zef install .
make emacs words closer to vim
20-10-21
%I love doomacs but jumping around words it bugged me underscores were not considered part of the word like in vim. After six months of dealing with it I stumbled upon a solution!
Simply put this in my .doom.d/config.el.
(modify-syntax-entry ?_ "w")
source: emacs.stackexchange
- [ emacs]
describing a raku variable
15-10-21
%My go to way to figure out what I'm working with in Raku.
my $res = cool_thing();
say $res.WHAT;
say $res.^attributes;
say $res;
- [ raku]
re-export javascript function
05-10-21
%When splitting logic into files in JavaScript it sometimes happens you have a folder of files; say for a single domain like Google analytics tracking. There comes a time in another part of the code where you need to import some functions and types from this GATracking folder but you may not want to dig into which file in the folder that function is. Re-exporting allows us to keep the API of the GATracking logic consise and allow the rest of the program to not worry about how exactly the files are structured. Example:
src/client/hooks/GATracking/index.tsx
export { default as TrackingAction } from './actions';
export const track = (action: TrackingAction) =>
...
Then somewhere else: src/client/components/GoButton/index.tsx
import {TrackingAction, track} from '../hooks/GATracking';
...
source: https://stackoverflow.com/questions/34576276/re-export-a-default-export
- [ js]
creating a temporary tabel in sqlite
21-09-21
%Today I needed to export some data from an sqlite tabel to csv, as part of my poverty line project. Using sqlitebrowser I could see the table had to much data and I only wanted to export a few columns. To accomplish this I learned how to create a temporary table and exported that.
DROP TABLE IF EXISTS processing_data_export;
CREATE TEMPORARY TABLE processing_data_export AS
SELECT x,y, county_id FROM grid;
source: stackoverflow
wipe dynamodb table via terraform
17-09-21
%Recently I came across the problem of how to wipe a dynamodb table. I though there would be an ui button for this or at lease an api/sdk method but from what I found the only way it to individually delete the items by key. This method can be batched up to 10 items per call but is still very slow and incurs write costs.
Since I'm used Terraform to create the table in the first place I thought I'll just destroy it and remake it... Then came the problem of not wanting to destroy everything but simply remake the table. After some digging in Terraform docs I found a pretty clean solution.
main.tf
module "dynamodb_table" {
source = "terraform-aws-modules/dynamodb-table/aws"
name = "poverty-line-county-gps-map"
hash_key = "id"
stream_enabled = false
attributes = [
{
name = "id"
type = "S"
}
]
tags = {
Terraform = "true"
Project = "poverty_line"
}
}
In this case I wanted to remake "poverty-line-county-gps-map". To find out what exactly it is called I ran terraform state:
$ terraform state list
aws_sqs_queue.dead_letter_queue
aws_sqs_queue.terraform_queue
module.dynamodb_table.aws_dynamodb_table.this[0]
from here the resource can be remake like:
$ terraform apply -replace="module.dynamodb_table.aws_dynamodb_table.this[0]"
Happy times remaking things. π
pushing to remote branch with different name
08-09-21
%Some times you rename a branch locally and want to push it to a remote branch with a different name. This is how:
$ git push -u origin localBranch:remoteBranch
source: stack-overflow
- [ git]
measuring node.js function performance
23-08-21
%How fast is that new function?
import { xx } from 'xx';
+import { performance } from 'perf_hooks';
@@ -160,7 +161,10 @@ const userSessionMiddleware = async (req: XRequest, res: ExpressResponse, ne
+ var t0 = performance.now();
req.isBot = headersIndicateBot(req.headers);
+ var t1 = performance.now();
+ console.log('Took', (t1 - t0).toFixed(4), 'milliseconds to calculate is bot');
source: https://www.sitepoint.com/measuring-javascript-functions-performance/
init yubikey
16-07-21
%Some servers at work require yubikey authentication and for some reason I have to fetch and verify every time I want to use it.
$ export SSH_AUTH_SOCK=~/.gnupg/S.gpg-agent.ssh
$ gpg --card-edit
fetch
verify
enter key
via pass yubikey
quit
$ ssh-add -L
$ ssh travis@serverX
add types to a javascript when using typescript
12-07-21
%Today I had a .js file that I needed to import into the rest of a TypeScript app but could not convert it to a .ts file. To get around this limitation I added an accompanying .d.ts file.
countryConfig.js
const countries = [
{
code: 'de',
domainExtension: '.de'
},
...
];
exports.countries = countries;
countryConfig.d.ts
interface Country {
code: string;
domainExtension: string;
}
export const countries: Array<Country>;
app.ts
import countries from './countryConfig'
...
source: https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-d-ts.html
- [ jstypescript]