[
  
    {
      "tags"     : "Android, Coil, Jetpack Compose",
      "title"    : "Adding accurate AsyncImage previews in Coil 3 with a Compose wrapper",
      "excerpt"  : "I recently migrated from Coil 2 to Coil 3, allowing remote image fetching to be overridden for better previews! Here’s a simple wrapper implementation.\n",
      "url"      : "/coil-asyncimage-previews/",
      "date"     : "Jan 30, 2026",
      "content"  : "I recently migrated from Coil 2 to Coil 3, allowing remote image fetching to be overridden for better previews! Here’s a simple wrapper implementation.\n\nIf you’ve built a UI with Coil and AsyncImage, you’re probably used to large blank areas in your previews. This doesn’t matter much if you have placeholders set, but this isn’t always the case. Luckily, LocalAsyncImagePreviewHandler allows arbitrary drawables to be used in previews.\n\nKotlin code\n\nFirst, here’s the entire utility function, in PreviewAsyncImage.kt:\n\n@OptIn(ExperimentalCoilApi::class)\n@Composable\nfun PreviewAsyncImage(\n    drawableResId: Int,\n    content: @Composable () -&gt; Unit\n) {\n    if (!LocalInspectionMode.current) {\n        error(\"PreviewAsyncImage should only be used in @Preview functions\")\n    }\n\n    val context = LocalContext.current\n    val previewHandler = remember(drawableResId) {\n        AsyncImagePreviewHandler {\n            val drawable = ContextCompat.getDrawable(context, drawableResId)\n            val bitmap = if (drawable is BitmapDrawable) {\n                drawable.bitmap\n            } else {\n                // Convert vector/other drawables to bitmap\n                val width = drawable?.intrinsicWidth?.takeIf { it &gt; 0 } ?: 1\n                val height = drawable?.intrinsicHeight?.takeIf { it &gt; 0 } ?: 1\n                val bitmap = createBitmap(width, height)\n                val canvas = android.graphics.Canvas(bitmap)\n                drawable?.setBounds(0, 0, canvas.width, canvas.height)\n                drawable?.draw(canvas)\n                bitmap\n            }\n            bitmap.asImage()\n        }\n    }\n\n    CompositionLocalProvider(LocalAsyncImagePreviewHandler provides previewHandler) {\n        content()\n    }\n}\n\n\nAnd here’s how to use it as a wrapper, where every AsyncImage will display preview_image:\n\n@Preview\n@Composable\nfun ComposableWithAsyncImagePreview() {\n    PreviewAsyncImage(R.drawable.preview_image) {\n        ComposableWithAsyncImage()\n    }\n}\n\n\nExplanation\n\nCoil does all the hard work for us in terms of overriding the preview, however we still need to actually obtain a bitmap. Since the drawable reference could be a bitmap (e.g. a .png) or vector (e.g. a .xml), we may need to place the drawable onto a canvas first.\n\nWe also have a guard at the start to ensure this is never run outside a @Preview context, since it’s conceivable a preview function’s contents could be copied without noticing the override.\n\nThe simple wrapper makes implementation easy across an entire codebase, helping improve preview accuracy and avoid accidental UI issues. Whilst it is also possible to directly map remote image calls to specific resources, that was not necessary for my use case.\n\nFinally, here’s the wrapper in action, as per the PR implementing it!\n\n\n"
    } ,
  
    {
      "tags"     : "Technology, Lenovo, Laptop",
      "title"    : "A real-world comparison between Lenovo's ThinkBook 16p Gen 2 and 16p Gen 6 (with photos!)",
      "excerpt"  : "I recently replaced my aging Lenovo ThinkBook 16p Gen 2 with a Gen 6, so here’s benchmarks, side-by-side photos, and general notes on their differences!\n",
      "url"      : "/thinkbook-gen-2-and-6-comparison/",
      "date"     : "Dec 3, 2025",
      "content"  : "I recently replaced my aging Lenovo ThinkBook 16p Gen 2 with a Gen 6, so here’s benchmarks, side-by-side photos, and general notes on their differences!\n\nScenario\n\nI use my laptop for mostly media watching / listening during the day whilst working on my MacBook, with a bit of programming and gaming (mostly Forza Horizon or Fallout). It stays closed 24/7, mounted under my desk, with 1x 1440p &amp; 1x 4K monitor connected.\n\nAs such, I need a “bit of everything” laptop. Decent CPU for code compiling, decent GPU for gaming, but also looks like a regular laptop and isn’t absurdly heavy or covered in RGBs. The ThinkBook 16p Gen 2 did a pretty good job at this, but the gaming performance was somewhat limited (not helped by me buying a 2-year old model!). Time to upgrade to a 2025 Gen 6!\n\nDisclaimer\n\nWhilst the technical specifications and benchmarks are presented as unbiased as possible, a laptop used daily for over 2 years is always going to have reduced performance. Despite closing any additional programs (e.g. Steam, WhatsApp), various things are probably running in the background and using up system resources, in additional to the typical hardware wear and tear.\n\nThe new laptop was fully set up before I used it, meaning it’s totally possible that a single misbehaving program (e.g. Lenovo Vantage, or Logi Options+) might be skewing the results. However, the entire point is a real-world comparison, so I don’t mind at all, hopefully you don’t either!\n\nSpecifications\n\nSince I was intending to buy the mid-high spec ThinkBook 16p Gen 6 at full price, a 20% Black Friday discount meant I could purchase the max spec ThinkBook 16p Gen 6 instead!\n\n\n  \n    \n      Feature\n      ThinkBook 16p Gen 2 ACH1\n      ThinkBook 16p Gen 6 IAX2\n      Improvement\n    \n  \n  \n    \n      Released\n      Q1 2021\n      Q3 2025\n       \n    \n    \n      Cost\n      £9893 (Mar ‘23)\n      £1,4204 (Nov ‘25)\n       \n    \n    \n      CPU\n      Ryzen 7 5800H\n      Intel Core Ultra 9 275HX\n      +80%5\n    \n    \n      GPU\n      RTX 3060 6GB\n      RTX 5060 8GB\n      +72%6\n    \n    \n      RAM\n      16GB DDR4-3200MT/s\n      32GB DDR5-5600MT/s\n      &gt;+250%\n    \n    \n      Storage\n      500GB SSD M.2 2280 PCIe 3\n      1TB SSD M.2 2242 PCIe 4\n      +200%\n    \n    \n      Screen\n      16” 2560x1600 60Hz\n      16” 3200x2000 165Hz\n      +56%\n    \n    \n      Battery\n      71Wh\n      85Wh\n      +20%\n    \n    \n      Charger\n      230W\n      300W\n      +30%\n    \n    \n      USB\n      2x USB-A, 2x USB-C 3.2\n      2x USB-A, 2x USB-C 4\n       \n    \n    \n      Wireless\n      Wi-Fi 6, Bluetooth 5\n      Wi-Fi 7, Bluetooth 5.4\n       \n    \n  \n\n\nBenchmarks\n\nBenchmarking tools\n\n\n  \n    \n      Type\n      Benchmark\n      ThinkBook 16p Gen 2\n      ThinkBook 16p Gen 6\n      Improvement\n    \n  \n  \n    \n      SSD\n      CrystalDiskMark Read\n      3591/2080/213/31\n      6607/3884/680/84\n      +84% - +219%\n    \n    \n      SSD\n      CrystalDiskMark Write\n      305/293/221/69\n      5855/2873/497/154\n      +123% - +1820%\n    \n    \n      CPU+GPU\n      3DMark Time Spy\n      6531 (CPU 7786, GPU: 6351)\n      11659 (CPU 16418, GPU 11092)\n      +78%\n    \n    \n      CPU+GPU\n      3DMark Steel Nomad\n      1472\n      2529\n      +74%\n    \n  \n\n\nObviously these are just benchmarks, so aren’t necessarily reflective of actual improvements. Regardless, the numbers are impressive, and reflect 4 years of technological progress. The SSD improvement across reads and writes is startling, as I didn’t know PCIe 3.0 -&gt; PCIe 4.0 would make such a difference! I was mainly just looking forward to 1TB, since 500GB was getting a little cramped. Sequential writes apparently benefited most from the upgrade, with an absurd +1820%.\n\nMore realistic however are the 3DMark benchmark improvements, which should be fairly close to real world performance. Both widely used tests agree on a 70-80% improvement in performance, which is enough to go from an unstable FPS playing games at high quality settings at 4K resolution, to an actually enjoyable experience.\n\nReal world comparisons\n\n\n  \n    \n      Benchmark\n      ThinkBook 16p Gen 2\n      ThinkBook 16p Gen 6\n      Improvement\n    \n  \n  \n    \n      Startup time seconds7\n      41.12s\n      17.39s\n      -58%\n    \n    \n      Jekyll build time seconds8\n      Cold: 21.50s, Warm: 12.52s\n      Cold: 7.4s, Warm: 4.37s\n      -65%\n    \n    \n      Forza Horizon 5 FPS9 (High, 4K)\n      55 (Sim: 159, Render: 98, GPU: 57)\n      60 (Sim 283, Render: 223, GPU 107)10\n      +78% - +127%\n    \n  \n\n\nIn addition to the benchmarks, here’s a time comparison for a few things I actually do day-to-day. Startup time, a programming-y task, and a gaming-y task. My anecdotal experience from the very start was a clearly snappier and more responsive system, although a lot of this is of course due to just being a clean system.\n\nThe results are about as expected, with the key difference for me being doubled performance on high graphics at 4K resolution. Whilst time saving during tasks is good, the ability to actually play games in high quality is a far more immediate benefit!\n\nPhotos\n\nOverall, the Gen 6 distinctly feels both more modern and more premium. Edges tend to be sharper, there are far fewer curves, and it gives off a bit of a “Cybertruck” vibe. The position of the “ThinkBook” and “Lenovo” branding also seems to have swapped around, who knows why.\n\nAdditionally, the ports are better placed, ventilation seems significantly better, and there seems to be a heavy MacBook inspiration on the keyboard. It’s clearly the same family of products as the Gen 2, but reflects a few years of design improvements.\n\nEdges\n\nIn these photos, the Gen 2 is on the bottom, therefore the Gen 6 is on the top.\n\n\n  \n    \n      Side\n      Photo\n      Notes\n    \n  \n  \n    \n      Front\n      \n      The Gen 6 is notably “chunkier” here, along with the “Magic Bay”11 connector.\n    \n    \n      Back\n      \n      The Gen 6 is very different here, with absolutely massive air vents, and the very sensible decision to have an HDMI connector here instead of 2x USB, and move it further away from the proprietary power port since it was extremely easy to confuse them (they look identical at a glance!).\n    \n    \n      Left\n      \n      The Gen 6 has kind of “swapped” left and right, with the 3x USB-C &amp; 2x USB-C ports now being entirely on the sides. Interestingly, the side vents have disappeared, presumably because of the giant rear vents.\n    \n    \n      Right\n      \n      No additional comments.\n    \n    \n      Front 2\n      \n      Side by side, the chunky Gen 6 clearly has far more space for hardware inside! It is slightly elevated due to the “Magic Bay”11 keeping it off the table, but there’s still a distinct difference.\n    \n  \n\n\nTop-down\n\nIn these photos, the Gen 2 is on the left, therefore the Gen 6 is on the right.\n\n\n  \n    \n      Scenario\n      Photo\n      Notes\n    \n  \n  \n    \n      Top\n      \n      A fairly similar design (besides the branding swap), although as a running theme the Gen 6 looks more modern.\n    \n    \n      Top (Partially open)\n      \n      The keyboard is mostly the same, but the clutter above the backspace has been replaced with a sensible Home / End / Delete / brackets, and additional Page Up / Down buttons have appeared next to the arrow keys. I don’t use the keyboard much, but I approve of the utility keys replacing gimmicky shortcuts (except the Copilot key!).\n    \n    \n      Top (Fully open)\n      \n      No additional comments, note that the pattern in the speaker is just a reflection.\n    \n    \n      Normal view\n      \n      The Gen 6 screen is noticeably higher (a bit better for posture), otherwise about the same.\n    \n    \n      Bottom12\n      \n      The Gen 6 footpads are noticeably larger, and the vent shape has changed. I would guess this is to avoid dust blocking the vents.\n    \n  \n\n\nNot noticeable in these images is a small improvement to the webcam privacy shutter: It now “sticks” to either side via magnets! Previously it would freely slide, meaning it often ended up pointlessly half-covered.\n\nMounted\n\nThis is only relevant to my under-desk mounting setup (documented here), the Gen 6 is a far better fit.\n\n\n  \n    \n      ThinkBook 16p Gen 2\n      ThinkBook 16p Gen 6\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nWith the new laptop mounted the other way round (back facing outwards) purely for USB-C port access, I gained multiple other benefits!\n\n\n  The laptop no longer pokes out a bit (very annoying!), although the power cable is still technically sticking out.\n  The heat ventilation is drastically improved. Previously it vented out the bottom (fine), and the back / sides where only a small amount of space was available before the desk infrastructure, so overheating was common. Now, it vents entirely into the room uninterrupted.\n  There is now a very accessible USB-A port next to where the USB-C monitors are connected, plus a couple more fairly accessible USB-A ports on the other side.\n\n\nSummary\n\nOverall, I’m very happy with the purchase! As with the occasional phone upgrade, I just wanted “the same, but better”, and that’s definitely what I got. After a few hours of setup, the new laptop feels almost identical13, with the only difference being essentially everything being speedier and more reliable. Yippee!\n\nHopefully this laptop lasts at least 2 more years, and is up to the task of playing Forza Horizon 6 when it releases in 2026 🤞.\n\nTech specs\n\n\n  Gen 2 tech spec: https://psref.lenovo.com/syspool/Sys/PDF/ThinkBook/ThinkBook_16p_G2_ACH/ThinkBook_16p_G2_ACH_Spec.pdf\n  Gen 6 tech spec: https://psref.lenovo.com/syspool/Sys/PDF/ThinkBook/ThinkBook_16p_G6_IAX/ThinkBook_16p_G6_IAX_Spec.pdf\n\n\nNotes\n\n  \n    \n      AMD processor: https://www.lenovo.com/gb/en/p/laptops/thinkbook/thinkbookp/thinkbook-16p-g2-ach/xxtbxpea600 &#8617;\n    \n    \n      Intel processor: https://www.lenovo.com/gb/en/p/laptops/thinkbook/thinkbookp/thinkbook-16p-gen-6-16-inch-intel/len101b0055 &#8617;\n    \n    \n      Purchased 2 years after release, hence the discount. &#8617;\n    \n    \n      Reduced from £1,850 for Black Friday, plus £45 student discount. Does not include the £108 in Lenovo Points. &#8617;\n    \n    \n      https://cpu.userbenchmark.com/Compare/Intel-Core-Ultra-9-275HX-vs-AMD-Ryzen-7-5800H/m2389974vsm1442974 &#8617;\n    \n    \n      https://gpu.userbenchmark.com/Compare/Nvidia-RTX-5060-Laptop-vs-Nvidia-RTX-3060-Laptop/m2416979vsm1452971 &#8617;\n    \n    \n      Informally measured by recording time between pressing power button and Windows login screen appearing. &#8617;\n    \n    \n      When deploying locally, the main process is generating the posts themselves, which includes a “done in X.XX seconds.” output. The first start is usually slower, with subsequent rebuilds (not incremental) being quicker. Incremental builds vary a lot depending on what has changed (and are 1-2 seconds), so would be hard to compare. &#8617;\n    \n    \n      High graphics preset, with all AI-y anti-aliasing turned off, at my monitor’s native 4K resolution. &#8617;\n    \n    \n      I play with VSync enabled, but FH5 doesn’t support my monitor’s actual refresh rate (75) so it’s locked to 60. As such, whilst the Gen 2 (at 99%+ GPU the entire time) 55 FPS is accurate, the Gen 6 (at 50-60% GPU) is closer to 105 FPS. In this scenario, “Sim” is the game simulation FPS, “Render” is the game rendering FPS, and “GPU” is how many frames the GPU is actually able to output, basically the frames per second. &#8617;\n    \n    \n      Lenovo’s very underused modular connector system, with only a webcam, light, or light available, all of which could be used with a USB port instead! &#8617; &#8617;2\n    \n    \n      A support barcode printed on the laptops has been censored here! &#8617;\n    \n    \n      Obviously helped significantly by using external monitors, headphones, keyboard, and mouse. &#8617;\n    \n  \n\n"
    } ,
  
    {
      "tags"     : "Steam, Automation",
      "title"    : "A detailed guide to automated farming & selling of Steam Trading Cards 🧑‍🌾🎴",
      "excerpt"  : "Steam Trading Cards have been out for a long time, but you probably didn’t realise you likely have tens of games with earning potential just sitting in your library! Here’s how to earn and sell the cards quickly.\n",
      "url"      : "/automating-steam-trading-cards/",
      "date"     : "Oct 11, 2025",
      "content"  : "Steam Trading Cards have been out for a long time, but you probably didn’t realise you likely have tens of games with earning potential just sitting in your library! Here’s how to earn and sell the cards quickly.\n\nWhat are cards?\n\nIn case you haven’t used them much, Steam Trading Cards (launched in 2011) are Steam inventory items earned by having eligible games open (e.g. paid games that have opted in). The cards have a few possible uses:\n\n\n  Sold on the Steam Market (what we’ll be doing).\n  Crafted into cosmetic badges for your profile (this is why people will be buying your cards).\n  Turned into gems for card booster packs (not worth it).\n\n\nUltimately though, all that matters is that they only require time to earn and can be sold for Steam Wallet currency. This is directly spendable on games or other inventory items, so is pretty close to just earning cash.\n\nFarming cards\n\nFirst, it’s worth checking that you have unearned cards. If you only play free games, or own very few games, you may not. Since I’ve purchased a few game bundles over the years, I had almost 1000 unearned cards!\n\nEligibility\n\nYou can check your eligibility by visiting the “Badges” page of your Steam Community profile whilst logged in, and searching for the word “PLAY” that is shown next to eligible games:\n\n\n\nAutomation overview\n\nSo, assuming you are eligible for card drops, let’s automate earning them. Whilst you could install every eligible game and run them until the cards are earned, this is a complete waste of both your time and your machine’s processing power!\n\nBy using automation software, we can instead report to Steam that the appropriate game is running. This allows you to just press start and leave your machine, using almost no system resources (12MB RAM for me) and skipping the arduous game downloading process.\n\nAdditionally, the automated process is optimised to factor in the variable per-game minimum time, utilising a somewhat complicated process of cycling between single and multi game idling called “Fast Mode” that would be very hard to perform manually.\n\nIdle Master Extended\n\nThere are a few automation tools available, I personally chose Idle Master Extended. Installing any software, especially one gaming-related, is always a risk. However, here’s why I decided this was safe:\n\n\n  The repository has 3k stars, plus an appropriate number of forks, watchers, issues, and pull requests for a project of this size. Malware will typically just have stars.\n  The project is stable, with no releases in 2.5 years. Considering Steam hasn’t changed much in that time, this is actually a good thing!\n  The project is mentioned often on Reddit and other places, with all the natural tech support questions and comparison between similar tools you would expect from real software.\n  It looks like a developer’s tool. Completely showing my bias here, the simple nature of the UI (screenshot below) clearly indicates a utility tool, exactly what we need. It’s also only 1MB big!\n\n\n\n\nNote: ArchiSteamFarm is far more popular (12k stars), however the regular releases, more complex setup process, request for your username and password(!) and serious complexity / feature set made it unappealing. We just need a simple tool!\n\nSetup\n\nIdle Master Extended has a nice and simple guide to getting started, but I’ll summarise here:\n\n\n  Download the latest idle_master_extended_vX.XX.X.zip file from the GitHub Releases, it’ll be just over 1MB.\n  Extract the zip somewhere.\n  Run the .exe, it’ll check Steam is running, then ask you to login.\n\n\nLogging in\n\nSince Idle Master Extended needs to join games and monitor card drops on your behalf, it needs to use your login token. This is obviously a risk, consider your own risk tolerance before proceeding. For me, it’s worth it, due to the reasons listed previously.\n\nTo find these details:\n\n\n  Go to https://steamcommunity.com (not the store!).\n  Open the developer console (F12, or “More tools” -&gt; “Developer tools” in Chrome).\n  Select the “Application” tab at the top.\n  Select “Cookies” under the “Storage” categories on the left, and click https://steamcommunity.com.\n  Look for your sessionId and steamLoginSecure.\n  Double click each in turn, and copy then paste into Idle Master Extended.\n\n\nOnce submitted, Idle Master Extended will log in, show “Idle Master is connected to Steam”, look up your card eligibility, and start farming cards.\n\nNote: Your session will expire every 2-3 days for security, indicated by Idle Master Extended showing an “X” next to logged in status, so you’ll memorise these steps pretty quickly!\n\n\n\nRunning\n\nIdle Master Extended’s default settings are typically exactly what you want, and it will try to automatically begin optimised idling on program startup. However, you can also configure features like shutting down Windows when done, or dark theme, in the “File” -&gt; “Settings” menu.\n\n\n\nWhilst running, your friends will receive lots of game open and close notifications, so you may want to turn these off! This can be done by setting your “Game details” to “Private” in your privacy settings.\n\n\n\nAnd now… you wait!\n\nCards drop at random intervals, so it’s hard to gain detailed estimates for the number of cards per hour. For me personally, I’ve used the tool for 6 days at around 12-16 hours a day (autorunning whenever my laptop is on), and have gone from 867 cards remaining to 488. If we estimate running for 14 hours a day, so 84 hours total, we get an average 4.2 cards earned per hour!\n\n\n  \n    \n      4th October\n      10th October\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nSelling cards\n\nOkay, so we’ve got some free cards, what do we do with them? Sell them!\n\nWhilst you can do this step automatically, it’s fairly slow to manually set an appropriate price for a few hundred items. Instead, we’re again going to rely on a “userscript” to do the heavy lifting for us.\n\nPreparing to sell\n\nUnfortunately, the tool we want to use can’t be run on Chrome. Instead, you’ll need to use Firefox, Brave, or whatever other browser you want to use. I used Firefox.\n\n\n  Install a userscript manager, I used Tampermonkey since it’s been widely used for a very long time. “Violentmonkey” is an alternative.\n  Install Steam Economy Enhancer by tapping “Install Steam Economy Enhancer”, then “Install” (next to Cancel).\n  Open up your Steam inventory, and you should see a new “Sell All Cards” button among others!\n  Additionally, market prices for your cards will start loading and being displayed:\n\n\n\n\nNote: There is also an extension “Steam Inventory Helper” with more advanced functionality, however it is full of shady adverts, wants quite extensive permissions, and has overgathered data before. I don’t recommend it!\n\nSelling\n\nTap “Sell All Cards” and… it’ll start! There’s also a “Sell All Items” option, but obviously don’t tap this if you have things you don’t want to sell (backgrounds, emotes, etc).\n\nOnce tapped, it’ll run through every marketable item you own, and tell you the sale price and your earnings after Valve &amp; the game’s commission (typically 1-2 pennies / cents per item). These cards won’t sell immediately, as most already have thousands listed. Instead, a few sales will trickle through every day as older sales are processed and your listings move closer to the front.\n\n\n\nNote: Sometimes this process gets “stuck” due to a failed request. Refreshing the page and tapping “Sell All Cards” again continues from where it paused.\n\nNote 2: Some cards (e.g. from delisted games) are not marketable. These can be converted into gems, but are almost worthless.\n\nConfirming\n\nHowever, there might be another reason the cards don’t sell: You haven’t confirmed them yet! Depending on your Steam Guard settings, you may need to approve every marketplace listing on your phone, a feature implemented to protect expensive items but a bit silly for hundreds of cheap ones.\n\nOpen up Steam on your phone, go to your notifications, tap “X pending confirmations”, and tap every single confirmation one at a time. Whilst there are ways to automate this (setting up your browser as a 2-factor device), for me personally this risked account security too much. As such, I just did it manually.\n\n\n\nNote: The app lags quite significantly when accepting lots of confirmations at once. Be patient, it’ll get there!\n\nNote 2: The selling process will begin failing with a “too many pending confirmations” error after 100-200 items listed, so you might want to regularly approve them as it autosells.\n\nProfitability\n\nSo how much will you actually earn from this?\n\nEach game will drop you half the cards needed for a badge (typically between 5 and 10), so 3-5 cards per game is a reasonable estimate. Cards for popular games will usually sell for between £0.04 and £0.07 depending on the game and number of cards in a set, resulting in a post-commission amount of £0.02 to £0.05. So, around £0.05-£0.15 per eligible game, which sounds pretty bad until you consider…\n\n\n  Foil cards: In addition to regular cards, you will sometimes find foil cards. These are usually worth 3-10x as much, with some obscure games having zero listed so you can name your own price in case someone is desperate to complete a collection!\n  Obscure games: For games with few players, the card price will be much higher (although liquidity will be lower). For example, in “Arcade Spirits”, my regular card is worth £0.12, whilst my foil card has no accepted price.\n  Booster packs: Once you have collected all the cards for a game, you are eligible for a booster pack. These are essentially blind boxes with 3 cards in, however they can be sold directly too (and this is usually slightly better profit than opening).\n\n\nThe random nature of foil cards and booster packs makes getting an average profit essentially impossible. For example, one of my obscure foil cards sold for £10, twice as much as the game itself!\n\n\n\nHowever, I would personally estimate around £0.16 per game once all lucky drops are factored in. So, for my 250 eligible games, I’d expect to receive around £40. Not bad for running some automated tools!\n\nNote: This doesn’t include the increased chance of future booster pack drops.\n\nIs it allowed?\n\nI guess technically not? However, is it enforced? Definitely not.\n\nValve have historically been very, very lenient with automation around the Steam platform (hence Team Fortress 2 trading bots, Steam Achievement Manager operating since 2008, and many more examples!), only stepping in when automation is disadvantaging other users (or Valve). In this case, we’re adding more cards into the economy, helping supply cards for rarely played games, and of course making Valve &amp; the game companies at least £0.01 per sale!\n\nAdditionally, the card drops are part of the perks of purchasing on Steam, so you’ve already paid for them. The automation just makes the farming much easier.\n\nWhilst it’s obviously impossible to say the tools recommended in this post are safe, it’s worth observing how their subreddits / discussions / GitHub issues don’t include any mentions of bans whatsoever despite tens of thousands of users.\n\nConclusion\n\nWith both the farming and selling stages requiring ~2 minutes setup work each, then just letting them run, getting the most out of your purchased games seems like a win-win for everyone (you, badge hunters, Valve, game publishers). I’d highly recommend this process to anyone with a substantial library, however obviously assess the risks yourself before starting.\n\nHappy farming! 🧑‍🌾🎴\n"
    } ,
  
    {
      "tags"     : "Google Play, Company, Payments, Privacy",
      "title"    : "Please don't dox me Google: How to verify your Google Play account without exposing ALL of your information",
      "excerpt"  : "In 2023, Google began requiring verification for Google Play, especially if earning any money. Unfortunately, this required publicly exposing your home address and phone number! Here’s how to earn money without revealing this info.\n",
      "url"      : "/publishing-on-google-play-without-exposing-info/",
      "date"     : "Jan 19, 2025",
      "content"  : "In 2023, Google began requiring verification for Google Play, especially if earning any money. Unfortunately, this required publicly exposing your home address and phone number! Here’s how to earn money without revealing this info.\n\nBefore we get started, this will require setting up a company and a forwarding address. Whilst there is a cost, in the UK neither of them are too tricky. I’d recommend Rapid Formations which offer this for around £67/yr, more on that later in “Solution”.\n\nTl;dr\n\nDon’t want to read the full post? No worries! Here’s the entire thing:\n\n\n  You’ll need to form a company in your country using a forwarding address.\n  You’ll then make a new “Organisation” Google Play profile, and verify it with your company’s info.\n  Finally, you’ll transfer your apps and all associated services, and delete your old profile.\n\n\nThat’s it! If any of it seems at all unclear, time to get into lots of detail as I document this process I never want to go through again! There’s also lots of tips around verification in this r/androiddev post.\n\nScenario\n\nIn July 2023, Google announced a controversial policy requiring all developers to verify this information. This sounded fairly innocent and easy, until looking at the detailed requirements for personal accounts. Specifically, if you’re earning money the following will be public:\n\n\n  Your legal name\n  Your phone number\n  Your legal address\n\n\nWhilst I’m happy sharing my legal name (it’s Jake Lee, could you tell?), my phone number and address are extremely private information! My phone number is both a way to contact me 24/7 and used for 2FA SMS in services that don’t support app-based, whilst my address is… literally where my family and I live. This should not be public, ever.\n\nIf you want to earn money, the only official options are:\n\n\n  Reveal all your information publicly.\n  Let Google close your account and remove all your apps.\n\n\nLuckily, there is a way to solve this in a Google- and privacy-friendly way by creating a new Google Play Console account. More details in “Solution” after information on / ranting about my personal scenario!\n\nPersonal scenario\n\nI’ve been earning money on Google Play since 2016, and once upon a time it earned more than my (low!) salary, encouraging me to become an Android developer, a job I love.\n\nWhilst my apps (e.g. Pixel Blacksmith) no longer earn significant amounts (typically £10-50/month), it’s still a nice bit of bonus money to fund other projects. Similarly, players are clearly still enjoying the apps, so the apps should stay available as long as possible!\n\nI did some work last year to get my old games running, conforming to Google Play’s latest requirements, and sorting out any policy paperwork that needed solving. There was still the developer verification, but that wasn’t required until 2025 so I left it. Now it’s time to solve it!\n\nFailed attempts\n\nBefore solving the issue, I failed multiple times. I’ll condense these multi-week stressful struggles into 2 summaries, and spare too many details.\n\nAttempt 1, Apr ‘24\n\nSince I already had a registered company with a forwarding address, I assumed I could use this as my personal address. However, proof of me as an individual at this address was required, such as a utility bill. This was impossible (I don’t live in an office!), and I went through multiple rounds of my company documents &amp; personal documents being rejected.\n\nThroughout this, I was sent various intimidating emails about Google Services being suspended, and when combined with unhelpful slow &amp; vague answers from Google Support, this was a pretty stressful experience.\n\nFor example, my Google One (extra storage) subscription was expiring. My Google Pay had been suspended, so it was impossible to renew (with any payment method whatsoever, including Google Play credit). If I hadn’t managed to resolve it in time, I would have had to deleted tens of GBs of photos / data to ensure my storage was within the free limit, otherwise I would have lost the ability to receive emails.\n\nLuckily, I managed to verify my personal address, and delay verification, allowing my payment profile to be unsuspended and pay for Google Pay. Problem not solved, but delayed.\n\n\n  \n    \n      Failed payment\n      Consequences\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nAttempt 2, Dec ‘24\n\nI had some time over Christmas, so time to try again!\n\nSince verifying as an individual failed, using the lessons learned from hours of Reddit thread reading, I decided to create a Google Play Console account with a new Google account (the one used for my company) as an organisation. I started the process, entered my company details, and was immediately suspended due to the details not being verified.\n\nSpecifically, I was told:\n\n\n  Because we’ve been unable to verify information for one or more users on your Google payments profile, your Google payments account has been suspended. Your Google services will continue temporarily, but some transactions may be suspended.\n\n  If action is not taken on this issue within 10 days, your Google services will be suspended.\n\n\nNo problem, it asks for a “Certificate of Incorporation” and I have that. I immediately submitted the files requested, a review time of 24-48 hours was mentioned, easily within the 10-day warning.\n\nAnd then I waited. And waited.\n\nWhilst waiting, I tried registering again, stating I didn’t want to earn money, to see if this made a difference. It did not.\n\nA week later, I received a 3-day warning, and nothing had changed. Well, it has been Christmas day, lots of holidays, so don’t need to panic quite yet.\n\nThen I received my 1-day warning. I don’t know what “Google services will be suspended” means, but it doesn’t sound good. In fact, since this email address is paying for Google Workspace and controls all my @jakelee.co.uk emails, this sounds very bad indeed.\n\nContacting support was, yet again, not particularly helpful. The agent couldn’t directly review documents, but did at least confirm my emails would not stop working due to the suspension. Hopefully there’s some sort of manual review required before a suspension, or they’re paused when there’s a large review backlog.\n\nEither way, the final 24 hours expired and… I didn’t receive any updates, but my email still worked. Okay, panic slightly over. Later on I received a casual email that my documents had been verified and all was now OK. Right. What a lot of pointless stress.\n\n\n  \n    \n      Emails received\n      1 day left\n      Pending cases\n    \n  \n  \n    \n      \n      \n      \n    \n  \n\n\nSolution\n\nSo, how can this be solved properly, and we can continue earning money whilst keeping private information private?\n\nPart 1: Preparing your details\n\nSetting up a company\n\nTo earn money, you will need to share a legal address, this is absolutely required. However, if you’re an organisation this can be your office address, which can be done with a virtual office address, since the government (at least in the UK) accepts them.\n\nSo, to set up a company without revealing your home address:\n\n\n  Set up a company (I already have Jake Lee Ltd).\n  Set up a forwarding address for your company (I pay £39/yr).\n  Set up a forwarding address for your personal correspondence (I pay £26/yr).\n  Request your D-U-N-S number (this is free).\n\n\nRapid Formations offer an all-in-one package that seems to do pretty much everything (including business bank account, domain name, and more). I only began using a virtual office after establishing my company, so cannot personally vouch for this service, only confirm that the virtual office service has been perfect.\n\nOkay, so you now have a legal company with a legal address. That’s the biggest hurdle overcome!\n\nSetting up contact details\n\nNext, you need to give Google some other information to list publicly:\n\nEmail: Google requires a public-facing &amp; Google-only email address. These can be the same, and don’t have any specific requirements besides being able to verify them. I’ve had a Google Play specific email address for years and only receive spam (usually about buying apps) once every few months.\n\nPhone: Similarly, Google will want a phone number to contact you, and a number for users to contact you. This is trickier, since you likely don’t want to give away your phone number. Whilst there are various ways to pay for a virtual number, the easiest way is just to request a free SIM card (e.g. from giffgaff), pop it in your phone to verify, then take it out or put in a spare phone.\n\nThis is a privacy trade-off (since a phone network now has your address), but I’m only concerned about public sharing of this information so it’s fine. I’ve changed networks enough that most of them know where I live!\n\nWebsite: You’ll need some sort of public website, verified via Google Search Console. There aren’t any specific requirements here.\n\nFinally, you’ll have an email address, phone number, and website you can use.\n\nPart 2: Creating a Google Play Console profile\n\nNow, you need to use your business’ information to form a Google Play Console profile, and a payments profile.\n\nSetting up an organisation\n\nNext up, you need to create a Google Play Console organisation. Organisations have a simpler verification process (presumably since they rely on existing company verification), which we can use.\n\nThis process is straightforward if you have all the prerequisites, specifically:\n\n\n  D-U-N-S number.\n  Certificate of incorporation for your company (available on Companies House under Filing History).\n  Contact information (phone, email, address).\n  $25 to pay the registration fee.\n\n\nDuring this process, you will be asked to set up a payments profile.\n\nSetting up a payment profile\n\nWhilst setting up an organisation will appear to succeed, it will actually fail, causing the fee payment at the very end to be rejected. At this point you will need to submit your Certificate of Incorporation.\n\nOnce you’ve submitted this, and it’s been reviewed (this can take a while, see “Attempt #2”), the “Settings” tab of your payment profile will finally show as verified:\n\n\n\nPutting it all together\n\nOnce your payment profile has been verified, and you have no outstanding alerts, you will need to register for a Google Play Console account again, select this payment profile, and attempt the fee payment again.\n\nThis time, it should succeed, and you’ll finally have a Google Play Console organisation account!\n\nOf course, as soon as you open it you’ll be told you need to verify it. Well, that’s easy now, we have our Certificate of Incorporation and other information from the payments profile. This only took a day or so for me, and didn’t require any new information.\n\nTidying up\n\nThere are various settings here you’ll likely want to fix. For example:\n\n\n  You’ll need to verify and link a bank account (Settings -&gt; Payments profile).\n  You’ll need to check your public information (email, description etc) are correct.\n  You’ll need to add a developer profile picture, and banner.\n  You’ll need to verify tax information for the USA and other countries. My payments got temporarily suspended (again) whilst doing this!\n\n\nOnce these changes and verifications have all gone through, you’ll have a verified Google Play Console organisation account! Phew, we’re getting closer.\n\nPart 3: Transferring apps\n\nGreat, now you’ve got a new, verified account, you need to transfer your apps! Luckily, this step actually has some official documentation containing the required steps.\n\nAccount group\n\nFirst, you’ll need to invite your new account to an “Account Group” (more info), accept the invite on the new account, and then make it the primary developer account.\n\nThis just lets Google knows your 2 profiles are related, and I suspect it makes the app transfer process a bit easier. Since the current profile is owned by you, and the new profile is owned by a company where you are the only shareholder… they’re linked pretty closely!\n\nSharing access\n\nNext, you need to make sure any Google-related services you’re using in your apps keep working once the apps have transferred.\n\nFor me this required giving my new account access to my apps’ Google Analytics, Google Cloud (for Google Play Games, and Maps API), and Firebase (for crash logs). You might also need to do the same for AdMob. The instructions vary by service, however this should be a simple process since it’s just adding a new user.\n\n\n  \n    \n      Firebase\n      Google Cloud\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nRequesting transfer\n\nOkay, it’s time to finally transfer your apps! This is surprisingly easy, with official documentation walking you through the process.\n\nOne complexity is you’ll need a “registration transaction ID” for your old and new developer account. This is the payment reference for your Google Play registration fee, created when you opened your account. For my old account I had to scroll through all my Google Play transactions back to 2016, for my new account it was in a recent email.\n\nPay close attention to Google’s (vague) advice here about the transaction ID. You need to remove placeholder-y prefixes from the ID, or the transfer will be rejected:\n\n\n  Important: When providing your transaction ID during the app transfer request process, remove the first part of the Order ID (for example, discard ‘0.G.’ or the digits before the words ‘token’ or ‘Registration’):\n\n\n\n  \n    \n      Old account\n      New account\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nTransferring\n\nOnce you’ve got your ID ready, and entered all the new account’s details, you can submit a request. I transferred an unused app first to check it worked, and then did the rest in one big go. You’ll receive a quite helpful email before the transfer, and one confirming the transfer has been successful.\n\nThis part was surprisingly easy after all the headaches of payment profiles and addresses. Both my transfers went smoothly, and it seemed like a well-oiled process!\n\n\n  \n    \n      Transfer confirmation\n      Pre-transfer email\n      Post-transfer email\n    \n  \n  \n    \n      \n      \n      \n    \n  \n\n\nYou’re done! A few hours / days / weeks of paperwork, and you’re finally done!\n\nWell, there’s a tiny bit of tidyup of course…\n\nPart 4: Tidying up\n\nWhilst your old Google Play profile now has no apps, it still has a verification deadline. To avoid any action being taken against your account (and to get $25 back!), you can submit a request to close your Google Play profile and get a registration refund.\n\nFor me this was 8 years after registering, and was done by submitting a request to their cancellation form. I received an email asking me to confirm the deletion, and which added card the money should be refunded to. Again, this went through smoothly, and the $25 was a nice surprise.\n\nI had a few extra payment profiles made during my various earlier attempts to resolve my verification issues, so these had to be closed too. They can only be closed if there’s no linked payments or accounts, including Google Play Console:\n\n\n\nIf your info was previously listed on the store, you may want to request its removal from Archive.org. Finally, you might want to remove access to Firebase / Google Cloud etc from your old account. I didn’t bother since it makes accessing the data a bit easier.\n\nConclusion\n\nThis was probably the most painful yet stressful experience I’ve gone through since buying my house, made significantly worse due to vague wording everywhere, nobody to talk to, and unknown consequences.\n\nWhilst it all ended well, and my apps are now listed with my business name &amp; address, the solution wasn’t obvious. Instead, on my personal account, I essentially just got threats and impossible requests. It took lots and lots of Googling to find the “create new account and transfer” solution, since it isn’t at all intuitive.\n\nI’d also like to give a massive shoutout to u/yiotro on r/androiddev for compiling a list of extremely helpful bits of advice about verification. The most helpful ones for me were:\n\n\n  \n    Individual accounts are not allowed to use anything other than a home address\n    Google doesn’t say this directly anywhere, but it is believed that account types must match, otherwise there will be problems.\n    If the payment profile is linked to a developer account, it is impossible to unlink it. You can only create new account from scratch and transfer your apps there.\n  \n\n\nThis process likely wouldn’t have had such a positive outcome if I hadn’t:\n\n\n  Had a career as an Android Developer, and therefore having any action taken against my account being a worst case scenario.\n  Had spare time and money to pay for the various services required to protect my privacy.\n\n\nFor a new Android engineer, or one with limited resources (e.g. a student), it seems impossible to actually publish apps earning any revenue without revealing all of their information to the world, forever. I understand the Google Play Store is primarily made for businesses (the verification process was painless when I did it for my employer), but you know how you get good Android engineers? By letting them experiment and try building their own apps, and maybe even making money from it.\n\nIf these rules had been in place back in 2016 when I published my first Android game, I’m not sure whether it would have ever been published. Without it, my career &amp; life would have taken a different, likely much less fulfilling and enjoyable, path.\n\nIt’s worth mentioning if you don’t make any money from your apps only your country and name is revealed, but for some people even this can be too much. For me personally, I have no idea why a customer in another continent considering playing my free game needs the ability to visit my home address! I guarantee they’re not going to get any technical support on the doorstep…\n"
    } ,
  
    {
      "tags"     : "Android, Play Store, Kotlin",
      "title"    : "Rapidly improving Play Store rating with an Android in-app review prompt helper (from 2.2 to 4.7 in 2 weeks!)",
      "excerpt"  : "I recently worked on an app, Seatfrog, that had been rated between 1 and 2 stars for months, despite no major issues. The solution? In-app rating prompts!\n",
      "url"      : "/play-store-rating-prompt/",
      "date"     : "Dec 26, 2024",
      "content"  : "I recently worked on an app, Seatfrog, that had been rated between 1 and 2 stars for months, despite no major issues. The solution? In-app rating prompts!\n\nAll code in this article is available as a GitHub Gist.\n\nPlay Store Rating\n\nLike a lot of people, I rely on an app’s Play Store rating as a rough indicator of quality / trustworthiness. Typically, anything below 4 stars needs a closer look, but above is probably fine. Despite this, the app I spend most of my time on was rated around 2.0! Time to fix that.\n\nWhy was the rating so low?\n\nHistorically, the app previously had a number of pretty severe problems. This included features not working, instability, unresponsive UI, etc. All of this resulted in an abysmal rating of 1.4 in February 2024.\n\nSince the app typically received just 2 - 5 reviews a week, almost all were from unhappy customers!\n\nBy steadily working through hundreds of raised bugs, aggressively improving stability by fixing every identified crash (currently 99.97% crash-free users!), and constantly improving overall quality, this slowly started improving. 9 months later, the app had steadily increased to a rating of 2.0 in November 2024, primarily by reducing the quantity of 1-star reviews.\n\nOn Google Play Console, under Monitor and Improve -&gt; Ratings and Reviews -&gt; Ratings, the number of ratings and rating distribution can be seen.\n\n\n\nWhilst this was a big improvement (the minimum is 1 star, so the number of non-1-star reviews was actually 4x higher!), it was nowhere near my acceptable level: 4.0+.\n\nWhat happened to the rating?\n\nReducing the number of 1-star reviews helped, but you know what would help even more? A flood of 5-star reviews! Continuing to receive feedback from unhappy customers is expected, and appreciated, so long as the thousands of satisfied customers are heard too.\n\nLooking at a chart of number of ratings over the past 3 months explains what happened. Instead of an occasional rating, literally hundreds of 4 and 5-star reviews flooded in, solving the problem within a couple of weeks:\n\n\n\nWith a regular release schedule, the per-version average rating can also be used to check which is responsible for the flood of reviews. It might be the version with at least 40x as many reviews as any other!\n\n\n\nHow was the rating improved?\n\nWith Google’s In-App Review Prompt library!\n\nBy prompting happy users with a very low-friction way to express their satisfaction, gathering high volumes of positive reviews was surprisingly painless. Google’s diagram describes the flow well:\n\n\n\nThe app itself has no direct control or observability of this rating prompt. Instead, it asks Google’s library to show the prompt if possible, and receives a callback when the prompt is finished. There are many, many, many reasons the callback might be called, all intentionally hidden from the app:\n\n\n  Rating prompt not shown because app was not installed from the store.\n  Rating prompt not shown because the user has already rated the app.\n  Rating prompt shown, user dismissed.\n  Rating prompt shown, user rated and submitted.\n\n\nAll of this is to ensure apps can’t reward (or punish!) the user based on their rating, or whether they rated at all. This is a good thing, and also means the app doesn’t need to worry about all the various outcomes!\n\nInstead, the app just needs to ask to show the prompt, and receive the callback when it’s finished. This isn’t too complicated, but I created a ReviewPromptHandler wrapper to drastically simplify usage.\n\nI defined a few specific triggers where the prompt would be shown if possible, specifically at moments where customers are engaged and have positive sentiment (e.g. clicking “Look at upgrade” after winning an auction).\n\nReview Prompt Handler\n\nSo, why add complexity to a fairly simple to use library? Well, there are a few requirements in my use case to keep customers, Google, and other developers in the codebase happy!\n\nRequirements\n\n\n  Simple to use: Any ViewModel that wants to display a review prompt shouldn’t need to keep track of the request status, handle errors etc. It should just be able to request the prompt’s appearance, and optionally pre-load.\n  Remotely configurable triggers: I want to be able to remotely control where this prompt appears. For example, I may want to disable it appearing after a successful bid due to some unrelated technical issue.\n  Triggered on button click or without specific interaction: The review prompt should be triggerable by a variety of trigger types^.\n  Able to remotely disable: In case there’s some catastrophic issue in Google’s library, I want the ability to ensure it isn’t relied upon at all if there’s no enabled triggers.\n  Requests aren’t spammed: Whilst Google doesn’t explicitly state quotas, they do say:\n    \n      “To provide a great user experience, Google Play enforces a time-bound quota on how often a user can be shown the review dialog.”\n      “Because the quota is subject to change, it’s important to apply your own logic and target the best possible moment to request a review.”\n    \n  \n\n\n^: Note that Google advises “you should not have a call-to-action option (such as a button) to trigger the API, as a user might have already hit their quota and the flow won’t be shown”, this is not applicable here since we’re using a callback to still perform the button’s usual function, not a dedicated CTA button!\n\nOkay, pretty sensible requirements. How can they be all be implemented?\n\nHandler flow\n\nThis is a quite technical diagram (it’s taken from my PR for the feature!), however it does show the main paths through the handler and prompt.\n\nTo clarify the 3 coloured sections:\n\n\n  Yellow: The rest of the app, usually the calling ViewModel. It knows almost nothing, and just calls functions.\n  Green: The ReviewPromptHandler.kt described in the next section. This abstracts all of the complexity away, and is the only class that interfaces with the in-app review prompt library.\n  Blue: Google’s in-app review prompt library, where all decision-making is intentionally obfuscated from the calling codebase.\n\n\n\n\nAs shown, the review prompt handler is going to have 2 callable functions (ignoring any initialisation), where ReviewPromptTrigger is a simple enum:\n\nfun prepareReviewPrompt(trigger: ReviewPromptTrigger)\nfun showReviewPrompt(trigger: ReviewPromptTrigger, callback: () -&gt; Unit = {})\n\n\nHandler code\n\nThe full code is available as a GitHub Gist, read on for an explanation.\n\nInitialisation\n\nUnfortunately, the library requires a Context to initialise (I used Application), and an Activity to display the prompt (I used my MainActivity).\n\nThis means a bit of non-ideal boilerplate and references to Activity:\n\n@Singleton\nclass ReviewPromptHandler @Inject constructor(\n    application: Application,\n    private val remoteConfigManager: RemoteConfigManager\n) {\n    private val reviewManager = ReviewManagerFactory.create(application)\n    private var activity: Activity? = null\n    ...\n    fun setActivity(activity: Activity) {\n      this.activity = activity\n    }\n\n\nRemote triggers\n\nAs mentioned, I want to be able to remotely configure my triggers. To implement this, I have a local enum of possible trigger points:\n\nenum class ReviewPromptTrigger(val remoteName: String) {\n    BID_MADE(\"BID_MADE\"),\n    BUN_PURCHASED(\"BUN_PURCHASED\"),\n    TICKET_PURCHASED(\"TICKET_PURCHASED\")\n}\n\n\nThen, I’m using Firebase Remote Config (any other remote value fetcher is fine) with a comma-separated review_prompt_triggers (e.g. BID_MADE,TICKET_PURCHASED). By checking the passed ReviewPromptTrigger is in the list of enabled triggers, remote control over the prompt is supported.\n\nAdditionally, I only want to prompt for the same trigger once per session, so I have a list of triggers that have fired.\n\nprivate val triggersThisSession = mutableListOf&lt;ReviewPromptTrigger&gt;()\n\nprivate fun shouldShow(trigger: ReviewPromptTrigger): Boolean {\n    if (triggersThisSession.contains(trigger)) {\n        return false\n    }\n    return remoteConfigManager.getString(review_prompt_triggers)\n        .split(\",\")\n        .map { it.trim() }\n        .contains(trigger.remoteName)\n}\n\n\nPre-caching review prompt\n\nGoogle’s advice on when to prepare a review prompt object is a little vague. Essentially you should request it before you ask the user, but it expires eventually:\n\n\n  Note: The ReviewInfo object is only valid for a limited amount of time. Your app should request a ReviewInfo object ahead of time (pre-cache) but only once you are certain that your app will launch the in-app review flow.\n\n\nIn my scenario, I pre-cache when the checkout flow starts, since this will typically result in a successful checkout (where the prompt will be used).\n\nUsing our shouldShow function from earlier, we request a review flow object and store the result in memory:\n\nfun prepareReviewPrompt(trigger: ReviewPromptTrigger) {\n    preparedReviewPrompt = null\n    if (!shouldShow(trigger)) {\n        return\n    }\n\n    reviewManager.requestReviewFlow().addOnCompleteListener { request -&gt;\n        if (request.isSuccessful) {\n            preparedReviewPrompt = request.result\n        }\n    }\n}\n\n\nDisplaying review prompt\n\nFinally, we can put this all together and actually show a prompt! I also decided to support the scenario where the caller didn’t have an opportunity to call prepareReviewPrompt.\n\nThis means there’s 2 flows (one with pre-caching (launchReviewPrompt), one without (prepareAndLaunchReviewPrompt)). If there’s no pre-caching, we fetch the review prompt object now instead, then display it once fetched. The trigger should also be added to the in-memory blacklist to avoid excessive requests.\n\nWe also must call the passed in callback no matter what happens, otherwise the user will get stuck on their current screen!\n\nfun showReviewPrompt(trigger: ReviewPromptTrigger, callback: () -&gt; Unit = {}) {\n    val activity = activity\n    if (!shouldShow(trigger) || activity == null) {\n        callback()\n        return\n    }\n\n    triggersThisSession.add(trigger)\n    preparedReviewPrompt?.let {\n        launchReviewPrompt(activity, it, callback)\n    } ?: prepareAndLaunchReviewPrompt(activity, callback)\n}\n\nprivate fun prepareAndLaunchReviewPrompt(activity: Activity, callback: () -&gt; Unit) {\n    reviewManager.requestReviewFlow().addOnCompleteListener { request -&gt;\n        if (request.isSuccessful) {\n            launchReviewPrompt(activity, request.result, callback)\n        } else {\n            Log.i(\"ReviewPromptHandler\", \"Failed to prepareAndLaunchReviewPrompt\")\n            callback()\n        }\n    }\n}\n\nprivate fun launchReviewPrompt(activity: Activity, reviewInfo: ReviewInfo, callback: () -&gt; Unit) {\n    reviewManager.launchReviewFlow(activity, reviewInfo).addOnCompleteListener {\n        if (!it.isSuccessful) {\n            Log.i(\"ReviewPromptHandler\", \"Failed to launchReviewPrompt\")\n        }\n        callback()\n    }\n}\n\n\nCalling the handler\n\nFinally, our handler is ready to use!\n\nAssuming ReviewPromptHandler has been injected or initialised, the TicketPurchaseViewModel prepares the prompt when checkout flow starts:\n\nreviewPromptHandler.prepareReviewPrompt(ReviewPromptTrigger.TICKET_PURCHASED)\n\n\nThen, when a prompt should be shown if possible (e.g. on button click), the Fragment passes in the normal post-button press action into the ViewModel:\n\nval navToBookings: () -&gt; Unit = {\n    findNavController().navigate(TicketFragmentDirections.toBookings())\n}\n...\nwhen (event) {\n    is TicketConfirmationEvents.OnLookAtMyTicket -&gt; {\n        viewModel.onLookAtMyTicket(navToBookings)\n    }\n\n\nWhere the ViewModel’s onLookAtMyTicket just calls ReviewPromptHandler with the correct ReviewPromptTrigger:\n\nfun onLookAtMyTicket(navigation: () -&gt; Unit) {\n    reviewPromptHandler.showReviewPrompt(ReviewPromptTrigger.TICKET_PURCHASED, navigation)\n}\n\n\nHow to test\n\nSimilar to testing whilst implementing Google’s force upgrade library, this can’t be tested easily on your local machine, and the app must be installed via the Google Play Store.\n\nThankfully, it’s far easier to test than force upgrade! Note that due to the “black box” of the library, you might not see the prompt despite following all the steps. Additionally, once you’ve seen one prompt, you might not see any others for a few weeks.\n\n\n  Prepare a build, and upload it to Google Play Console internal app sharing.\n  Uninstall your app from your device.\n  Add your device’s primary email address to the “In-app review testing” list on Google Play Console.\n  Open Google Play Console’s internal app sharing link on your device.\n  Install the app from this link.\n  Click your triggers, and make sure your callback actually happens (far more important than the review prompt appearing).\n\n\nYou’ll see slightly different messages when testing via internal app sharing vs a production app:\n\n\n  \n    \n      Internal app sharing\n      Production\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nNote: The oddly zoomed-in app icon happens on my device for all prod apps, presumably it’s a Google / Samsung issue!\n\nExtra notes\n\nMonitoring store rating\n\nTo keep an eye on my app’s rating throughout this process, I checked the Google Play Console once or twice a day.\n\nWhilst there is a Google Play Console app (which is rated 2.8!), and it has attractive data visualisations, the data updates are painfully slow. The data was typically 12 hours behind Google Play Console web, which is itself 12-24 hours behind!\n\nThe main number is the “Default Google Play rating” on the “Ratings” screen. This will show your overall Google Play rating, and should be treated as your source of truth. However, each individual device will see a slightly different score (due to OS, device type, etc), so there’ll be a slight spread around this value.\n\n\n\nCurrently, the Google Play Console app is the only way to see charts of Google Play rating and many other KPIs (Key Performance Indicators) over time:\n\n\n  \n    \n      Overview\n      Specific metric\n      KPI list\n    \n  \n  \n    \n      \n      \n      \n    \n  \n\n\nSpeed of increase\n\nWhilst Google Play Console does have an “Average rating over time” chart, this won’t match up with your displayed store rating due to how Google weights reviews based on time.\n\nAs such, I had to manually keep a note each day of the rating! Once the version with review prompting was rolled out to 100% (12th December), the rating improved by 0.1 to 0.5 per day(!):\n\n\n  19/11/24: 2.088\n  09/12/24: 2.187\n  11/12/24: 2.249\n  12/12/24: 2.327\n  13/12/24: 2.719\n  14/12/24: 2.819\n  15/12/24: 3.335\n  16/12/24: 3.796\n  17/12/24: 3.922\n  18/12/24: 4.082\n  19/12/24: 4.145\n  20/12/24: 4.317\n  21/12/24: 4.390\n  22/12/24: 4.498\n  23/12/24: 4.589\n  24/12/24: 4.638\n  25/12/24: 4.667 🎄\n\n\nAn increase from 2.2 to 4.7 in exactly 2 weeks is absolutely amazing (and an excellent Christmas present), and far exceeded my expectations for this project!\n\nCached rating\n\nA rapid rise in rating for a well-established app is pretty unusual, so other services will take multiple weeks or months to notice this rating has changed.\n\nFor example, whilst the store itself currently shows a rating of 4.7 for Seatfrog, Google Search results show a far lower rating from around July!\n\n\n\nConclusion\n\nAdding an in-app review rating prompt had an unbelievably rapid improvement to my app’s rating.\n\nI’d absolutely recommend adding a prompt to pretty much any app, with the resulting rating score essentially depending on how well you pick your triggers. If you prompt whilst the user is frustrated, putting a pop-up in their face is going to make things even worse!\n\nI see in-app review prompts pretty regularly for other apps, however they are usually implemented in a seemingly untargeted way. For example, 2 I saw recently were obviously triggered by the number of times the app has been opened, when I didn’t have a particularly positive sentiment and was just trying to complete a task. As such, I dismissed instead of rating.\n\nWhilst I did begin working on an “after X days” prompt, I eventually decided a smarter implementation was prompting less often but in a more targeted way. It seems to have been the correct call, with almost every review being 5-star.\n\nAs I write the first draft of this article, the app is sitting around 4.3, and still rising by 0.1 - 0.2 per day, expected to end up at 4.8 (average rating is 4.825). The next rating goal? 4.9!\n\nOne last time, all code used is available on GitHub: https://gist.github.com/JakeSteam/c09c7bd980095a8a26649419d49d393e\n"
    } ,
  
    {
      "tags"     : "Python, SQLite, Regex",
      "title"    : "Generating a SQLite word dictionary (with definitions) from WordNet using Python",
      "excerpt"  : "I recently needed a SQLite dictionary with word, type, and definition(s). Turns out, it was easy enough to make my own!\n",
      "url"      : "/sqlite-word-dictionary-from-wordnet/",
      "date"     : "Dec 18, 2024",
      "content"  : "I recently needed a SQLite dictionary with word, type, and definition(s). Turns out, it was easy enough to make my own!\n\nAll code in this article is available in a WordNetToSQLite repo, as is the final words.db database (license).\n\nObjective\n\nFor an upcoming word game app, I needed a dictionary of words. I wanted to know the type of word (noun / verb / adjective / adverb), and a definition for each. Plus, it should only include sensible words (e.g. no proper nouns, acronyms, or profanity).\n\nI decided to prefill a SQLite database and ship it with my app, since I can easily update it by just shipping a new database (or even remotely with SQL!). Android also has good support for retrieving the data from SQLite.\n\nHowever, finding a suitable list of words was tricky! I found plenty of sources containing just words, or with no information on source or licensing. Eventually, I discovered Princeton University’s WordNet exists, and luckily it’s free to use and has a very liberal license. There’s also a more up to date fork (2024 instead of 2006).\n\nHowever, it contains a lot of unneeded information and complexity, and is 33MB+ uncompressed. Time to get filtering…\n\nRunning script\n\nIf you wish to recreate words.db from scratch, or customise the results, you can:\n\n\n  Obtain a WordNet format database.\n    \n      I used a regularly updated fork (2024 edition, WNDB format)\n      You can also use the original WordNet files from 2006 (WNdb-3.0.tar.gz from WordNet)\n    \n  \n  Extract your download, and place the data.x files in /wordnet-data/.\n  Run py wordnet-to-sqlite.py.\n  In a minute, you’ll have a word database!\n\n\nOut of the box, the script takes ~60 seconds to run. This slightly slow speed is an intentional trade-off in exchange for having full control over the language filter (see profanity removal).\n\nNotes on results\n\nThe database contains over 71k word &amp; word type combinations, each with a definition. I use the open source DB Browser for SQLite to browse the results, looking something like this:\n\n\n\nSchema definition\n\nOnly one definition per word for the same type is used (e.g. with the noun article, but not the verb):\n\n\n  word:\n    \n      Any words with uppercase letters (e.g. proper nouns) are removed.\n      Any 1 character words are removed.\n      Any words with numbers are removed.\n      Any words with other characters (apostrophes, spaces) are removed.\n      Most profane words (626) are removed.\n      Roman numerals are removed (e.g. XVII).\n    \n  \n  type:\n    \n      Always adjective / adverb / noun / verb.\n    \n  \n  definition:\n    \n      Definition of the word, uses the first definition found.\n      Most profane definitions (1124) are replaced with empty space.\n      May contain bracketed usage information, e.g. (dated).\n      May contain special characters like ', $, !, &lt;, [, etc.\n    \n  \n\n\nNotes on code\n\nWhilst wordnet-to-sqlite.py is under 100 lines of not-very-good Python and doesn’t do anything too crazy, I’ll briefly walk through how it works.\n\nRaw data\n\nThe raw data in WordNet databases looks like this (unknown is the only valid noun to extract, with a single definition):\n\n08632096 15 n 03 unknown 0 unknown_region 0 terra_incognita 0 001 @ 08630985 n 0000 | an unknown and unexplored region; \"they came like angels out the unknown\"\n\n\nFurther notes on WordNet’s data files are here, this Python script just does a “dumb” parse then filters out numerical data and invalid words (spaces, capitalised letters, Roman numerals etc).\n\nProcess\n\n\n  For each word type file (data.noun, data.adj, etc), pass it to parse_file.\n  Loop through every line in this file, primarily using split / range to fetch as many words as are defined, without taking the 0 and other non-word data.\n  Check each of these words is “valid”, specifically that it’s lowercase letters only (no symbols / spaces), isn’t a Roman numeral (by matching the word &amp; description), and isn’t a profane word.\n  If the word is valid, add it to the dictionary so long as it isn’t already defined for the current word type. For example, a word might be used as a noun and an adjective.\n  Finally, output all these word, type, and definition rows into a SQLite database we prepared earlier.\n\n\nLuckily, as Python is a very readable language, function definitions almost read like sentences:\n\ndef is_valid_word(word, definition):\n    return (\n        word.islower() and\n        word.isalpha() and\n        len(word) &gt; 1 and\n        not is_roman_numeral(word, definition) and\n        not is_profanity(word)\n    )\n\n\nProfanity removal\n\nSince this dictionary is for a child-friendly game, profane words should be removed if possible. Players are spelling the words themselves, so I don’t need to filter too aggressively, but slurs should never be possible.\n\nThe eventual solution is in /profanity/, where wordlist.json is the words to remove, manually-removed.txt &amp; manually-added.txt are the words I’ve manually removed from / added to the wordlist, and log.txt is every removed word &amp; definition.\n\nChoice of package\n\nI tried out quite a few Python packages for filtering out the profane words, with pretty poor results overall. They were generally far too simple, required building a whole AI model, were intended for machine learning tasks, or seemed entirely abandoned / non-functional.\n\nEventually, I used better_profanity 0.6.1 for filtering (0.7.0 has performance issues), and whilst it was fast, it missed very obvious explicit words, whilst triggering hundreds of false positives. However, this was the best package so far despite being semi-abandoned, so I used it for most of the project (before rolling my own).\n\nWord list\n\nWith a 4 year old wordlist, missing quite common slurs wasn’t too surprising. As such, I tried using a much more comprehensive wordlist (2823 words vs better profanity’s 835). At this point, the library’s “fuzzy” matching was far too fuzzy, and half the words had their definitions removed!\n\nAfter logging all the removed words and definitions, I also noticed this list was quite over-zealous. I ended up manually removing 123 words (see whitelisted.txt), since words like “illegal”, “kicking”, “commie” are absolutely fine to all but the most prudish people. Removing false positives took the total number of profane removals from 3,368 to 1,750, all of which seem sensible.\n\nWhilst I now had a good word list, at this point I gave up using libraries, and decided to just solve it myself. It’s fine if the solution is slow and inefficient, so long as the output is correct.\n\nUsing regexes\n\nI implemented a solution that just checks every word (&amp; word of definition) against a combined regex of every profane word. Yes, this is a bit slow and naive, but it finally gives correct results!\n\nwith open(wordlist_path, 'r', encoding='utf-8') as f:\n    profane_words = set(json.load(f))\ncombined_profanity_regex = re.compile(r'\\b(?:' + '|'.join(re.escape(word) for word in profane_words) + r')\\b', re.IGNORECASE)\n\n\nThe script takes about a minute to parse the 161,705 word candidates, pull out 71,361 acceptable words, and store them in the database. Fast enough for a rarely run task.\n\nOptimisation\n\nA few steps are taken to improve performance:\n\n\n  executemany is used to insert all the database rows at once.\n  A combined (very long) regex is used since it’s far faster than checking a word against 2700 regexes.\n  A set is used for the word list, so words can be quickly checked against it.\n  Only one definition for each word &amp; type is included, as this reduces the database size from 7.2MB to 5.1MB.\n\n\nConclusion\n\nThe approach taken to generate the database had quite a lot of trial and error. Multiple times I thought I was “done”, then I’d check the database or raw data and discover I was incorrectly including or excluding data!\n\nSQLite Browser was extremely useful during this process, as the near-instant filtering helped me check profane words weren’t slipping through. It also helped me catch a few times when technical data would leak into the definitions.\n\nI’ll absolutely tweak this script a bit as I go forward (I’ve implemented all my initial ideas since starting the article!) and my requirements change, but it’s good enough for a starting point. Specifically, next steps are probably:\n\n\n  Try the WordNet 3.1 database instead of 3.0, and see if there’s any noticeable differences (there’s no release notes!) Tried, not much change\n  Use an open source fork, since it has yearly updates so should be higher quality than WordNet’s 2006 data. Done!\n  Replace the current profanity library, since it takes far longer than the rest of the process, and pointlessly checks letter replacements (e.g. h3ll0) despite knowing my words are all lowercase letters. Done!\n  Use the word + type combo as a composite primary key on the database, and ensure querying it is as efficient as possible. Done! Increased database size by ~20%, so will see if it’s necessary.\n\n"
    } ,
  
    {
      "tags"     : "GitHub, Design, Cats",
      "title"    : "What on earth is an Octocat!? Exploring all 160+ variations of GitHub's mascot",
      "excerpt"  : "If you’ve used GitHub for any length of time, you’ve probably seen their odd “Octocat” logo. This cute little cat also has a lot of bizarre variations, here’s an explanation of them all!\n",
      "url"      : "/what-on-earth-are-octocats/",
      "date"     : "Dec 7, 2024",
      "content"  : "If you’ve used GitHub for any length of time, you’ve probably seen their odd “Octocat” logo. This cute little cat also has a lot of bizarre variations, here’s an explanation of them all!\n\nThe (mostly) full list of octocats is available in GitHub’s “Octodex”, and they can to be used to refer to GitHub or as a personal avatar picture, but (unsurprisingly) not for commercial purposes or physical products. They’re very, very cute, and they definitely deserve more visibility. Maybe this article will help!\n\nWho is Mona the Octocat?\n\nMona (Lisa) the Octocat’s story has been described in absorbing, first-hand detail by Cameron McEfee, the man who has created more octocats than anyone, including the first 13 adaptations! There’s also an entire art book and stickers.\n\nTo summarise, in 2011 illustrator Cameron McEfee was tasked with adapting GitHub’s existing stock image mascot “Octopuss” (picked as a reference to git’s “octopus merge”) for use in GitHub’s error pages, and he gave it costumes and personality.\n\nThese were so popular that “50% of GitHub’s lifetime Twitter traffic was generated by my first week’s work” (source), very impressive for an error page illustration! This then led to many, many, many more adaptations, and the creation of the Octodex.\n\nSince then, many artists have created octocats in evolving styles, and it continues to feature prominently in most of GitHub’s communications. Some Octocat descriptions are only possible due to information from former employees, thanks!\n\nStandard Octocats\n\nClassic Octocats\n\nFirst up, the earlier Octocat variants. They are still very clearly variants on the original Octocat, and typically have a 2D, face-on appearance, with limited details and a recognisable stance. Whilst some have a modified position or other characters, they’re all easily identifiable as Octocat.\n\nThe majority of Pop Culture Octocats and around half of the Real People Octocats are from this fruitful period.\n\nThis era lasted from early 2011 to late 2012.\n\n\n  \n    \n      \n      #1: OriginalSimon Oxley (2011-03-23)\n      The Octocat that started it all, originally named \"Octopuss\"!\n    \n    \n      \n      #2: Class ActCameron McEfee (2011-03-28)\n      Used as promotional material for a party. Was also used to highlight PSD diffing.\n    \n    \n      \n      #4: PuppeteerCameron McEfee (2011-03-30)\n      Most likely used for something related to the Puppeteer web automation tool.\n    \n    \n  \n    \n      \n      #5: ScottocatCameron McEfee (2011-03-30)\n      This is most likely Scott Chacon, a GitHub co-founder with a similar profile picture.\n    \n    \n      \n      #6: BenevocatsCameron McEfee (2011-03-31)\n      Presumably a play on \"benevolent\", used for GitHub's Global Indigenous CoB.\n    \n    \n      \n      #7: ForktocatCameron McEfee (2011-03-31)\n      Included in early onboarding docs, a reference to \"Fork\"ing a repository. Reused for Neurocats Employee Resource Group.\n    \n  \n  \n    \n      \n      #8: RepoCameron McEfee (2011-03-31)\n      Included in early onboarding docs, a reference to repositories.\n    \n    \n      \n      #9: SetuptocatCameron McEfee (2011-03-31)\n      Included in early onboarding docs.\n    \n    \n      \n      #10: SocialiteCameron McEfee (2011-03-31)\n      Included in early onboarding docs, specifically around social features.\n    \n  \n  \n    \n      \n      #11: DrupalcatCameron McEfee (2011-04-01)\n      A reference to the Drupal CMS.\n    \n    \n      \n      #12: PythocatCameron McEfee (2011-04-01)\n      A reference to the Python language, used for Python related posts.\n    \n    \n      \n      #14: BouncerCameron McEfee (2011-04-03)\n      Most likely used for real life merchandise for (real world!) office security.\n    \n  \n  \n    \n      \n      #15: OctonautCameron McEfee (2011-04-04)\n      A play on \"Astronaut\".\n    \n    \n      \n      #19: SwagtocatCameron McEfee (2011-04-09)\n      A reference to free items from the CodeConf 2011 event.\n    \n    \n      \n      #23: InspectocatJason Costello (2011-04-13)\n      Likely a reference to a browser's \"Inspect Element\" feature. This was the first octocat not by Cameron McEfee!\n    \n  \n  \n    \n      \n      #25: AgendacatJason Costello (2011-04-15)\n      An agenda, presumably also used in relation to CodeConf 2011.\n    \n    \n      \n      #29: Total Eclipse of the OctocatCameron McEfee (2011-04-19)\n      Created for an Eclipse IDE related article, with a pun on the 1983 song \"Total Eclipse of the Heart\".\n    \n    \n      \n      #30: ConstructocatJason Costello (2011-05-01)\n      Probably used for \"Under Construction\" screen(s).\n    \n  \n  \n    \n      \n      #31: CollabocatsJason Costello (2011-05-02)\n      A play on the word \"collaboration\".\n    \n    \n      \n      #32: SupportcatJason Costello (2011-05-03)\n      Presumably used in relation to help / support.\n    \n    \n      \n      #33: Cherryontop-o-catJason Costello (2011-05-04)\n      Unknown\n    \n  \n  \n    \n      \n      #36: JenktocatCameron McEfee (2011-05-12)\n      A reference to the Jenkins CI system.\n    \n    \n      \n      #37: PoptocatCameron McEfee (2011-05-13)\n      Likely a play on \"Pop\", since there is also a \"Momtocat\". Used for Father's Day in June.\n    \n    \n      \n      #38: ScarletteocatJordan McCullough (2011-05-14)\n      Created by a former employee for his daughter Scarlette.\n    \n  \n  \n    \n      \n      #40: Dodge, Duck, Dip, Dive, DodgetocatCameron McEfee (2011-05-16)\n      A reference to The Five D's of Dodgeball from the film Dodgeball. Used for inter-company dodgeball tournaments.\n    \n    \n      \n      #41: Not OctocatCameron McEfee (2011-06-10)\n      Translates from French into \"this is not an octopus cat\".\n    \n    \n      \n      #43: Bear CavalryCameron McEfee (2011-07-02)\n      A reference to the \"Bear Cavalry\" meme popular at the time.\n    \n  \n  \n    \n      \n      #44: SpectrocatCameron McEfee (2011-07-02)\n      Unknown, possibly just a play on \"Spectre\".\n    \n    \n      \n      #47: ShoptocatCameron McEfee (2011-07-05)\n      Themed after an employee who handled merchandise.\n    \n    \n      \n      #48: OktobercatCameron McEfee (2011-07-06)\n      A reference to Oktoberfest.\n    \n  \n  \n    \n      \n      #51: Hipster PartycatJina Anne (2011-07-09)\n      Likely used for \"a company party invitation\" as mentioned on the creator's CV.\n    \n    \n      \n      #53: Father TimeoutJason Costello (2011-10-02)\n      Used to \"soften errors with cuteness\". A play on \"Father Time\".\n    \n    \n      \n      #54: Grim RepoCameron McEfee (2011-10-27)\n      A play on \"Grim Reaper\", created purely for the excellent pun.\n    \n  \n  \n    \n      \n      #55: Octocat De Los MuertosCameron McEfee (2011-10-28)\n      A reference to the Mexican holiday Dia de los Muertos (Day of the Dead).\n    \n    \n      \n      #61: ThanktocatCameron McEfee (2011-11-23)\n      A reference to the holiday Thanksgiving.\n    \n    \n      \n      #62: Ordered ListocatCameron McEfee (2011-12-05)\n      Used to announce GitHub's acquisition of \"Ordered List\".\n    \n  \n  \n    \n      \n      #63: Saint NicktocatCameron McEfee (2011-12-05)\n      A play on Saint Nick / Santa Claus.\n    \n    \n      \n      #66: DojocatCameron McEfee (2012-01-18)\n      Made for stickers at GitHub's \"CoderDojo\" sessions.\n    \n    \n      \n      #70: CodercatCameron McEfee (2012-02-15)\n      Represents a generic user, in the likeness of an employee at the time.\n    \n  \n  \n    \n      \n      #71: ElectrocatCameron McEfee (2012-02-29)\n      Used for GitHub's \"Security and IT\" jobs, possibly something to do with making connections.\n    \n    \n      \n      #72: Snow OctocatCameron McEfee (2012-03-05)\n      A reference to Mac OS X Snow Leopard.\n    \n    \n      \n      #73: MomtocatTony Jaramillo (2012-05-13)\n      A reference to Mom / Mum, used for Mother's day around this time.\n    \n  \n  \n    \n      \n      #75: Red PoloCameron McEfee (2012-06-21)\n      A reference to Scott Guthrie, a senior leader at Microsoft who often wears a red polo. Unknown purpose.\n    \n    \n      \n      #78: DroidtocatTony Jaramillo (2012-07-09)\n      Used for the first GitHub Android app release in July 2012.\n    \n    \n      \n      #82: DeckfailcatMatt Graham (2012-08-02)\n      Something related to the Speaker Deck software, possibly used as their 404 page.\n    \n  \n  \n    \n      \n      #119: Private InvestocatJames Kang (2015-01-27)\n      Presumably a reference to private investigators, often used for security related articles. Also used on the original GitHub Security Bounty page.\n    \n  \n\n\nModern Octocats\n\nAfter the “Classic” octocats and their relatively static appearances came the “Modern” octocats, with each clearly being a distinct piece of art, often with a unique position. Although Tony Jaramillo created the first of this era (Dodgetocat v2), it’s James Kang who really churned out creations!\n\nThis era lasted from late 2012 to late 2014.\n\n\n  \n    \n      \n      #85: Dodgetocat v2Tony Jaramillo (2012-10-25)\n      Another dodgeball cat, for another dodgeball event.\n    \n    \n      \n      #90: SkitchtocatJon Rohan (2012-12-15)\n      Presumably a reference to the screen annotating software Skitch (now owned by Evernote, previously used often by GitHub), as evidenced by the octocat being made up of arrow annotations.\n    \n    \n      \n      #91: MotherhubbertocatJames Kang (2013-01-27)\n      Possibly a reference to an internal piece of software.\n    \n  \n  \n    \n      \n      #92: RobotocatJames Kang (2013-01-28)\n      A robotic octocat, unknown purpose.\n    \n    \n      \n      #94: Professortocat v2James Kang (2013-02-11)\n      A stereotypical professor with an apple and cane, used for GitHub Education originally, and other training related posts.\n    \n    \n      \n      #95: KimonotocatJames Kang (2013-02-27)\n      A reference to the Japanese clothing Kimono, possibly used for a Heroku-related event.\n    \n  \n  \n    \n      \n      #96: MardigrastocatJames Kang (2013-02-27)\n      A reference to Mardi Gras, occurring a few days after this released.\n    \n    \n      \n      #97: Poptocat v2Tony Jaramillo (2013-04-19)\n      An iteration on the earlier \"Pop\" octocat, possibly for Father's Day in a couple of months.\n    \n    \n      \n      #101: FemalecodertocatJames Kang (2013-07-01)\n      A female version of \"Codercat\".\n    \n  \n  \n    \n      \n      #102: OctolibertyJames Kang (2013-07-05)\n      A reference to the Statue of Liberty.\n    \n    \n      \n      #104: LabtocatJoao Ribeiro (2013-08-18)\n      Possibly a reference to some sort of \"feature lab\", unknown.\n    \n    \n      \n      #106: SteroidtocatJames Kang (2013-12-13)\n      A reference to steroids, possibly a replacement for \"Bouncer\".\n    \n  \n  \n    \n      \n      #107: YaktocatJames Kang (2013-12-13)\n      Created for a Thai conference sponsorship, probably the Thai traditional \"Khon\", especially this image.\n    \n    \n      \n      #112: SaritocatJoao Ribeiro (2014-04-30)\n      Created for an Indian conference sponsorship, and often used for India-related posts.\n    \n    \n      \n      #113: LuchadortocatJames Kang &amp; Joao Ribeiro (2014-09-26)\n      Created for a conference sponsership (presumably Mexican), a reference to Mexican wrestlers (Luchadors).\n    \n  \n  \n    \n      \n      #114: SaketocatJames Kang (2014-09-27)\n      Created for a Japanese conference sponsorship, a reference to Japanese rice wine sake.\n    \n    \n      \n      #115: MinertocatJames Kang (2014-09-29)\n      An octocat panning for gold, unknown usage.\n    \n  \n\n\nExtra Modern Octocats\n\nTowards the end of 2014, something unusual happened to Octocat! It gained more detailed features, distinctive expressions, eyes, and other facial features, and it is clearly not a human. The limbs seem much “stretchier”, and the character is in much more active poses.\n\nMany of these images were used for temporary landing pages, promotional material, and other short-lived content. As such, finding the actual source or reason behind their creation can be tricky!\n\nThis era started in late 2014 (primarily due to Joao Ribeiro’s work, his many years of Octocat-related work are here) and is still dominant, with minor changes along the way. Internally this is called “Octocat 2.0” style.\n\n\n  \n    \n      \n      #116: JetpacktocatTony Jaramillo (2014-11-11)\n      Created for the launch for GitHub Enterprise, now used for GitHub's integrations organisation.\n    \n    \n      \n      #120: FilmtocatJames Kang (2015-04-29)\n      Created as a reference to GitHub's internal video team, now used for GitHub's \"Marketing and Communications\" jobs.\n    \n    \n      \n      #121: WelcometocatTony Jaramillo &amp; Joao Ribeiro &amp; Joel Glovier (2015-11-16)\n      Used for welcome emails, and similar introductory / congulatory material. There are multiple designs.\n    \n  \n  \n    \n      \n      #122: InflatocatRuby Jazz (2016-09-21)\n      A reference to inflatable pool toys, for unknown use.\n    \n    \n      \n      #124: SkatetocatSuzie Jurado (2016-11-16)\n      Unknown use, reference to skateboarding\n    \n    \n      \n      #128: DinotocatHaley Carroll &amp; Kim Estoesta (2017-05-15)\n      Created for National Dinosaur Day.\n    \n  \n  \n    \n      \n      #130: Saint Nictocat (v2)Haley Carroll (2017-12-18)\n      A reference to Saint Nicholas, for Christmas a week later!\n    \n    \n      \n      #132: JusticetocatHaley Carroll (2018-03-01)\n      Used for GitHub's \"Corporate, External, and Legal Affairs\" jobs, originally created for Women's History Month.\n    \n    \n      \n      #133: SnowtocatHaley Carroll (2018-03-20)\n      Reference to skiing, used for social media post.\n    \n  \n  \n    \n      \n      #134: TentocatHaley Carroll &amp; Joao Ribeiro &amp; Cameron Foxly (2018-04-10)\n      Used to celebrate 10 years since GitHub's official launch.\n    \n    \n      \n      #135: VinyltocatJoao Ribeiro &amp; Suzie Jurado (2018-04-21)\n      Unknown use, reference to vinyl records.\n    \n    \n      \n      #136: ScubatocatCameron Foxly (2018-06-05)\n      Reference to National Scuba Month.\n    \n  \n  \n    \n      \n      #138: SurftocatJames Kang (2018-06-14)\n      Reference to surfing, unknown purpose.\n    \n    \n      \n      #140: UmbrellatocatRuby Jazz (2018-09-13)\n      Used for a GitHub Field Day event.\n    \n    \n      \n      #141: SentrytocatCameron McEfee (2018-10-09)\n      Used for a GitHub / Sentry partnership post.\n    \n  \n  \n    \n      \n      #144: FintechtocatCecilio Ruiz (2019-06-18)\n      A reference to fintech (Financial technology), used to announce partnership with Fintech Open Source Foundation.\n    \n    \n      \n      #150: ManufacturetocatHaley Carroll (2021-03-04)\n      Unknown use, reference to manufacturing.\n    \n    \n      \n      #152: YogitocatJoao Ribeiro (2021-04-06)\n      Used to celebrate the launch for GitHub India.\n       \n  \n  \n    \n      \n      #154: GodotocatJoao Ribeiro &amp; Lee Reilly (2023-03-21)\n      Used to announce a Godot 4.0 Release Party.\n       \n    \n      \n      #156: SponsortocatCameron Foxly (2024-12-12)\n      Presumably used in relation to the GitHub Sponsors program.\n       \n    \n      \n      #157: UniversetocatCameron Foxly (2024-12-12)\n      Used for GitHub Universe 2024, with Mona the Octocat accompanied by Copilot (AI). The wings are code brackets, and the icon on her head is a commit, as discussed in an accompanying video.  \n       \n  \n  \n    \n      \n      #158: SecurityknightocatCameron Foxly (2024-12-17)\n      Unknown, presumably used in relation to some sort of GitHub verification / security, perhaps Advanced Security due to similar \"checkmark shield\" designs (also note Copilot on the belt, and commit / fork icons on armour).\n    \n    \n      \n      #159: SecuritocatCameron Foxly (2025-01-17)\n      Used for the \"EkoParty 2024\" event.\n    \n    \n      \n      #162: Bombacatkuuchen (2026-01-14)\n      An octocat performing a \"Bomba\" dance, unknown usage.\n    \n  \n  \n    \n      \n      #163: PartymartytocatCameron Foxly (2026-10-30)\n      Unknown, released during GitHub Universe 2026 so likely related. \n    \n  \n\n\nAnimated Octocats\n\n\n  \n    \n      \n      #46: NyantocatCameron McEfee (2011-07-04)\n      A recreation of the Nyan Cat meme.\n    \n    \n      \n      #99: Daftpunktocat-GuyJames Kang (2013-06-10)\n      A reference to Guy in Daft Punk.\n    \n    \n      \n      #100: Daftpunktocat-ThomasJames Kang (2013-06-10)\n      A reference to Thomas in Daft Punk.\n    \n  \n  \n    \n      \n      #105: MummytocatTony Jaramillo (2013-10-31)\n      A mummy, used in a gaming post but originally created for halloween.\n    \n    \n      \n      #108: MaxtocatJames Kang (2013-12-25)\n      A reference to Christmas (released on Christmas day!), unknown purpose. \n    \n    \n      \n      #109: GrinchtocatTony Jaramillo (2013-12-26)\n      A reference to the Grinch character &amp; Christmas (released on Boxing day!), unknown purpose. \n    \n  \n  \n    \n      \n      #110: CarlostocatJames Kang (2014-01-01)\n      A reference to the baby Carlos from The Hangover film, possibly due to partying on New Year's Eve the day before!\n    \n    \n      \n      #117: Gobble-o-tronTony Jaramillo &amp; Joao Ribeiro (2014-11-27)\n      A reference to Thanksgiving (a Turkey's noise is often described as \"gobble gobble\").\n    \n    \n      \n      #137: HulatocatHaley Carroll (2018-06-11)\n      A reference to the Hawaiian dance Hula, for unknown purpose. Possibly just social media post.\n    \n  \n  \n    \n      \n      #153: NUXtocatCameron Foxly (2021-07-19)\n      A reference to \"New User Experience\" (NUX), hence the capitalisation, not the framework \"nuxt\"! Used for sign-up flow.\n    \n  \n\n\nPop Culture Octocats\n\nA surprising number of the octocats are drawn in the style of a TV show or other pop culture characters!\n\n\n  \n    \n      \n      #3: Octobi Wan CatnobiCameron McEfee (2011-03-29)\n      A reference to Obi-Wan Kenobi from Star Wars, used on 404 page. The first public variation (along with this Wile E. Coyote reference)!\n    \n    \n      \n      #16: TrekkieCameron McEfee (2011-04-05)\n      A reference to Geordi La Forge from Star Trek.\n    \n    \n      \n      #21: SpocktocatCameron McEfee (2011-04-11)\n      A reference to Spock from Star Trek.\n    \n  \n  \n    \n      \n      #22: Jean-Luc PicatCameron McEfee (2011-04-12)\n      A reference to Jean-Luc Picard from Star Trek.\n    \n    \n      \n      #24: IroncatCameron McEfee (2011-04-14)\n      A reference to Iron Man.\n    \n    \n      \n      #26: Octoclark KentocatCameron McEfee (2011-04-16)\n      A reference to Superman AKA Clark Kent.\n    \n  \n  \n    \n      \n      #27: Okal-EltocatCameron McEfee (2011-04-17)\n      A reference to Superman AKA Kal-El.\n    \n    \n      \n      #28: Blinktocat, Pinktocat, Inktocat, and ClydeCameron McEfee (2011-04-18)\n      A reference to the 4 ghosts (Blinky, Pinky, Inky, Clyde) in Pac Man.\n    \n    \n      \n      #34: ChellocatCameron McEfee (2011-05-10)\n      A reference to Chell from Portal.\n    \n  \n  \n    \n      \n      #35: X-tocatCameron McEfee (2011-05-11)\n      A reference to Wolverine from X-Men.\n    \n    \n      \n      #42: AndycatJordan McCullough (2011-07-01)\n      A reference to the \"Shot Marilyns\" series of paintings by Andy Warhol.\n    \n    \n      \n      #50: RiddlocatCameron McEfee (2011-07-08)\n      A reference to Riddler from Batman.\n    \n  \n  \n    \n      \n      #52: Where's WaldocatJason Costello (2011-10-01)\n      A reference to the Where's Wally / Waldo series.\n    \n    \n      \n      #56: BaracktocatCameron McEfee (2011-10-29)\n      A reference to Barack Obama's \"Yes We Can\" slogan.\n    \n    \n      \n      #57: OctotronDiana Mounter (2011-10-29)\n      A reference to the Tron series of films.\n    \n  \n  \n    \n      \n      #58: PlumberCameron McEfee (2011-11-04)\n      A reference to Mario.\n    \n    \n      \n      #59: LinktocatCameron McEfee (2011-11-14)\n      A reference to Link.\n    \n    \n      \n      #60: MegacatJason Costello (2011-11-18)\n      A reference to Mega Man.\n    \n  \n  \n    \n      \n      #67: Doctocat BrownJon Rohan (2012-01-19)\n      A reference to Doc Brown from Back to the Future.\n    \n    \n      \n      #68: Adventure CatJon Rohan (2012-01-22)\n      A reference to Finn from Adventure Time.\n    \n    \n      \n      #69: StrongbadtocatCameron McEfee (2012-02-13)\n      A reference to Strong Bad from Homestar Runner.\n    \n  \n  \n    \n      \n      #74: 20% Cooler OctocatCameron McEfee (2012-06-13)\n      A reference to Rainbow Dash from My Little Pony.\n    \n    \n      \n      #76: HeisencatJon Rohan (2012-07-03)\n      A reference to Heisenberg (aka Walter White) from Breaking Bad.\n    \n    \n      \n      #79: MinionNick Hengeveld (2012-07-11)\n      A reference to Minions from Despicable Me.\n    \n  \n  \n    \n      \n      #80: HomercatNick Hengeveld (2012-07-13)\n      A reference to Homer Simpson from The Simpsons.\n    \n    \n      \n      #81: MurakamicatBilly Roh (2012-07-31)\n      A reference to Mr. DOB by Takashi Murakami.\n    \n    \n      \n      #83: PusheencatBilly Roh (2012-08-13)\n      A reference to Pusheen.\n    \n  \n  \n    \n      \n      #84: StormtroopocatJames Kang (2012-10-15)\n      Based on Star Wars' Stormtrooper, created when \"[GitHub] asked James to design the Octocat he thought the Octodex was missing most and he completely dazzled [GitHub] with his Stormtroopocat\"\n    \n    \n      \n      #86: Megacat v2James Kang (2012-10-25)\n      A reference to Mega Man.\n    \n    \n      \n      #87: SpidertocatJames Kang (2012-10-25)\n      A reference to Spider-Man.\n    \n  \n  \n    \n      \n      #88: Dr. OctocatJames Kang (2012-10-26)\n      A reference to Doctor Octopus from Spider-Man\n    \n    \n      \n      #89: GangnamtocatJames Kang (2012-10-31)\n      A reference to Gangnam Style by Psy.\n    \n    \n      \n      #103: DunetocatJoao Ribeiro (2013-08-18)\n      A reference to Dune.\n    \n  \n  \n    \n      \n      #111: TopguntocatLee Reilly &amp; Tony Jaramillo (2014-04-11)\n      Created as the logo for an internal app, possibly related to video streaming. A reference to Top Gun.\n    \n    \n      \n      #123: BewitchedtocatHaley Carroll (2016-10-31)\n      A reference to the sitcom Bewitched, used for Halloween themed posts.\n    \n    \n      \n      #139: BoxertocatRuby Jazz (2018-07-08)\n      Used for GitHub's 2017 GDC afterparty, likely a reference to Street Fighter's Ryu.\n    \n  \n  \n    \n      \n      #142: FilmtocatsHaley Carroll (2018-12-20)\n      A reference to GitHub's internal video team.\n    \n    \n      \n      #151: Mona the RivetertocatJoao Ribeiro (2021-03-08)\n      A reference to Rosie the Riveter.\n    \n    \n  \n\n\nReal People Octocats\n\nSome are based on real people, a mixture of historical figures, current celebrities, and even GitHub employees.\n\n\n  \n    \n      \n      #13: Founding FatherCameron McEfee (2011-04-02)\n      A reference to the USA Founding Father George Washington.\n    \n      \n      \n      #17: MonroeCameron McEfee (2011-04-06)\n      A reference to Marilyn Monroe, see also \"Andycat\".\n    \n    \n      \n      #20: WilsonCameron McEfee (2011-04-10)\n      A reference to Brian Wilson, a baseball player.\n    \n  \n  \n    \n      \n      #45: Octdrey CatburnCameron McEfee (2011-07-03)\n      A reference to Audrey Hepburn, an actress. A similar image was used for a charity OctoGala.\n    \n    \n      \n      #49: VisionaryCameron McEfee (2011-07-07)\n      A reference to Steve Jobs, former Apple CEO.\n    \n    \n      \n      #65: DefunktocatJason Costello (2012-01-13)\n      Styled after GitHub Co-founder Chris Wanstrath (aka defunkt).\n    \n  \n  \n    \n      \n      #93: GoretocatJames Kang (2013-02-03)\n      A reference to Frank Gore, american football player.\n    \n    \n      \n      #98: Founding Father v2James Kang (2013-05-24)\n      A reference to the USA Founding Father George Washington.\n    \n    \n      \n      #118: GracehoppertocatJames Kang (2014-12-03)\n      A reference to Grace Hopper, an early computer scientist. Also previously used for Octovets CoB.\n    \n  \n  \n    \n      \n      #125: McEfeelineTony Jaramillo (2017-01-27)\n      A reference to Cameron McEfee who made an overwhelmingly number of early Octocats, and \"had the foresight to dress up our feline cephlapod for the first time\".\n    \n    \n      \n      #127: Benjamin BannekatHaley Carroll &amp; Tony Jaramillo &amp; Joao Ribeiro (2017-02-28)\n      A reference to Benjamin Banneker, a mathematician, created for unknown purposes.\n    \n    \n      \n      #129: Mona LovelaceHaley Carroll (2017-12-12)\n      A reference to Ada Lovelace (Mona is Octocat's nickname), created for her 202nd birthday.\n    \n  \n  \n    \n      \n      #126: CatstelloTony Jaramillo (2017-01-28)\n      A reference to \"Jason Costello\", who created a few Octocats! Apparently \"Originally bred in the hills of New Jersey, it has migrated west spreading good vibes, stunning design, and an unapologetic bias towards proper typography\".\n    \n    \n      \n      #143: BrennatocatJoao Ribeiro (2019-03-29)\n      Styled after a former GitHub employee.\n    \n  \n\n\nNon-Standard Octocats\n\nNot Octocats\n\nSome of the octocats… are not octocats! They’re robots, clouds, crabs, and dogs.\n\n\n  \n    \n      \n      #18: HubotCameron McEfee (2011-04-07)\n      Hubot is GitHub's mostly internal chatbot platform that enables automations like translating texts. Used for all bot-related content, and in animations.\n    \n    \n      \n      #39: CloudCameron McEfee (2011-05-15)\n      A reference to GitHub being a \"cloud\" service.\n    \n    \n      \n      #64: NemesisCameron McEfee (2012-01-09)\n      A reference to BitBucket (\"Herme T. Crab, codes not socially, but alone\"), only ever used in a minigame mockup.\n    \n  \n  \n    \n      \n      #77: OctofezNick Hengeveld (2012-07-04)\n      A portrait of the artist's dog.\n    \n  \n\n\nSeries Octocats\n\nFinally, a few octocats are part of a series. These are used for internal Employee Resource Groups.\n\n#131: Blacktocats by Cameron Foxly (2018-02-21)\n\nCreated for GitHub’s Black Employee Resource Group.\n\n\n  \n    \n    \n    \n  \n  \n    \n    \n    \n  \n  \n    \n  \n\n\n#145: Adacats by Cameron Foxly (2020-01-08)\n\nCreated for GitHub’s Gender Minorities Employee Resource Group.\n\n\n  \n    \n    \n    \n  \n  \n    \n    \n    \n  \n\n\n#146: Octogatos by Cameron Foxly (2020-02-24)\n\nCreated for GitHub’s Latinx Employee Resource Group.\n\n\n  \n    \n    \n    \n  \n  \n    \n    \n    \n  \n\n\n#147: Terracottocat by Chubbmo (2020-03-05)\n\nCreated for the Chinese GitHub community.\n\n\n  \n    \n    \n  \n\n\n#148: Octoqueer by Cameron Foxly &amp; Tony Jaramillo &amp; Joao Ribeiro (2020-03-13)\n\nCreated for GitHub’s LGBTQ Employee Resource Group.\n\n\n  \n    \n    \n    \n  \n  \n    \n    \n    \n  \n\n\n#149: OctoAsians by Cameron Foxly (2020-09-28)\n\nCreated for GitHub’s Asian Employee Resource Group.\n\n\n  \n    \n    \n    \n  \n  \n    \n    \n    \n  \n  \n    \n  \n\n\n#155: Parentocats by Joao Ribeiro (2023-07-14)\n\nLikely created for GitHub’s parents Employee Resource Group.\n\n\n  \n    \n    \n    \n  \n  \n    \n    \n  \n\n\n#160: Neurocats by kuuchen (2025-04-15)\n\nCreated for Neurocats Employee Resource Group.\n\n\n  \n    \n    \n    \n  \n  \n    \n    \n    \n  \n  \n    \n  \n\n\n#161: Octovets by kuuchen (2025-07-22)\n\nCreated for Octovets Employee Resource Group.\n\n\n  \n    \n    \n    \n  \n  \n    \n    \n    \n  \n  \n    \n  \n\n\nUndocumented Octocats\n\nIn addition to the 150+ documented octocats in the Octodex, there are tons of other ones hidden all over the place if you keep an eye out!\n\nFor example, GitHub’s blog posts often have unique octocats (many many many examples on each word), as do third party sites working with GitHub (e.g. AppCanary). Many early blog posts now have broken images, so it’s likely many octocats were used there.\n\nSome of these undocumented octocats are mentioned on GitHub’s Dribbble, or individual designers’ sites, and almost all end up eventually used in GitHub’s social media posts (LinkedIn, GitHub, Facebook).\n\nCameron McEfee in particular (the artist behind the first “batch” &amp; many more) often shares unpublished examples on Mastodon (examples one, two, three, four, five).\n\nFinally, don’t forget you can create your own Octocat too!\n\nStatistics\n\nNote: Tables in this section count series as 1 each, and uses this Python code to parse the XML data.\n\nOctocats By Artist\n\nWith all the excellent artwork in this post, credit absolutely has to be given to the talented artists who created them. These are typically designers creating promotional octocats, but in the early days some designers clearly created them as a hobby hence all the pop culture references (Cameron McEfee, James Kang)!\n\nLater on, many octocats were created in formats not suitable for the Octodex (e.g. these amazing pieces featuring 30+ in one!), so the totals here only cover those explicitly added to the Octodex. It’s likely that the creators of the “Extra Modern” style have probably created far more, they’re just not documented.\n\nI’ve also heard rumours of an upcoming increased focus on Mona the Octocat, so there’ll presumably be more names and numbers coming soon!\n\n\n  \n    \n      Artist\n      Count\n    \n  \n  \n    \n      cameronmcefee\n      58\n    \n    \n      jeejkang\n      27\n    \n    \n      johncreek\n      15\n    \n    \n      tonyjaramillo\n      14\n    \n    \n      cameronfoxly\n      14\n    \n    \n      heyhayhay\n      11\n    \n    \n      jasoncostello\n      11\n    \n    \n      jonrohan\n      4\n    \n    \n      rubyjazzy\n      3\n    \n    \n      nickh\n      3\n    \n    \n      kuuchen\n      3\n    \n    \n      leereilly\n      2\n    \n    \n      suziejurado\n      2\n    \n    \n      billyroh\n      2\n    \n    \n      chubbmo\n      1\n    \n    \n      ceciliorz\n      1\n    \n    \n      kimestoesta\n      1\n    \n    \n      jglovier\n      1\n    \n    \n      mattgraham\n      1\n    \n    \n      broccolini\n      1\n    \n    \n      jina\n      1\n    \n    \n      jordanmccullough\n      1\n    \n    \n      simon\n      1\n    \n  \n\n\nI really like how many employees have only ever created one, with some perhaps only being a temporary intern yet still getting a chance to make permanent mark on the culture.\n\nOctocats By Year\n\nSomewhat less positively, looking at the octocats added to the Octodex over time shows how drastically this has decreased over time. Part of this is presumably GitHub growing and becoming less willing to release impulsive octocats (like Walter White!), but I suspect an even bigger part is a lack of interest in updating the Octodex. New octocats are being created (see Undocumented Octocats), they’re unfortunately just not being recorded.\n\nThe creator of the first Octocat adaptation (Cameron McEfee) maintained the Octodex in the early days, so it’s perhaps unsurprising that it does not include all octocats 13 years after the first batch!\n\n\n  \n    \n      Year\n      Count\n    \n  \n  \n    \n      2011\n      63\n    \n    \n      2012\n      27\n    \n    \n      2013\n      19\n    \n    \n      2014\n      9\n    \n    \n      2015\n      3\n    \n    \n      2016\n      3\n    \n    \n      2017\n      6\n    \n    \n      2018\n      12\n    \n    \n      2019\n      2\n    \n    \n      2020\n      5\n    \n    \n      2021\n      4\n    \n    \n      2023\n      2\n    \n    \n      2024\n      3\n    \n    \n      2025\n      3\n    \n    \n      2026\n      2\n    \n  \n\n\nConclusion\n\nIn conclusion… I love Mona the Octocat. It’s quite unusual that a stock image used initially for a tech startup survives nearly 15 years later, let alone with enough popularity to have an art book, figurine, and sculpture of them!\n\nIt’s a great way to give a bit of personality to what could be a bland, megacorp-owned, code management website (looking at you BitBucket…), and obviously instantly earns goodwill amongst cat fans. No, it doesn’t quite make sense (what does a cat really have to do with code!?), but that’s half the appeal, a little bit of quirk.\n\nIt’s a shame the Octodex is not as updated as it used to be, and GitHub’s recent focus on AI (and the not-quite-as-cute Copilot icon) has made Mona a little less visible than she used to be. However, I suspect she’ll come back, perhaps with yet another evolution!\n\n\n  \n    \n    \n    \n  \n\n“Walk cycles” animations by Tony Jaramillo, from “The Octocat - a nerdy household name“.\n"
    } ,
  
    {
      "tags"     : "Jekyll, Liquid, Optimisation",
      "title"    : "How to automatically add WebP post banners to Jekyll for faster load times",
      "excerpt"  : "Most modern browsers can handle the smaller &amp; speedier WebP versions of images, yet generating them manually can be a pain! Here’s how to do it automatically in Jekyll.\n",
      "url"      : "/adding-automated-webp-banners-to-jekyll/",
      "date"     : "Nov 30, 2024",
      "content"  : "Most modern browsers can handle the smaller &amp; speedier WebP versions of images, yet generating them manually can be a pain! Here’s how to do it automatically in Jekyll.\n\nI recently updated my site template to support automatic WebP conversion for the banners of every post. This requires both generating the files, and serving them correctly, with no extra manual effort.\n\nA full Gist of this post is available.\n\nGenerating WebP files\n\nThere’s a library that can do this all for us, unsurprisingly called jekyll-webp!\n\nSetting it up is straight-forward:\n\n\n  Add jekyll-webp to your Gemfile.\n  Add jekyll-webp to your _config.yml’s plugins section.\n  Finally, add a webp config object into your _config.yml. Below are the settings I use, a description of each is available on the repo:\n\n\nwebp:\n  enabled: true\n  quality: 95\n  img_dir: [\"/assets/images/banners\"]\n  nested: true\n  regenerate: false # Set to true if settings have been changed\n  formats: [\".jpeg\", \".jpg\", \".png\"]\n\n\nOnce the configuration is set up, run bundle install then bundle exec jekyll serve, and any images in /assets/images/banners will have a WebP version generated!\n\n\n\nDisplaying webp files\n\nNow the post’s banners are in WebP format, they need to be displayed safely and only to browsers that can support them.\n\nPrep work\n\nFirst, we need to create a webp.html somewhere. I used _includes/custom/webp.html.\n\nNext, we need to include it wherever we want our WebP / other image formats to appear. For me, this is my home.html &amp; post.html files, where I want to display the image inside an a tag:\n\n&lt;a class=\"post-link\" href=\"{{ post.url | relative_url }}\"&gt;\n  {% include custom/webp.html path=post.image alt=post.title %}\n&lt;/a&gt;\n\n\nMake sure the path and alt parameters map to something useful in your template!\n\nNote: If you don’t already have a post.html / home.html page because you’re using a template’s defaults, GitHub has guidance on how to create them.\n\nChecking WebP file exists\n\nNext, we need to build our webp.html to show these WebP banners if the user’s browser supports them, and they’ve been successfully generated.\n\nJekyll templates use the quite limited language Liquid, so we have to do some quite tedious string manipulation to:\n\n\n  Remove the extension from the file’s path (e.g. .png, .jpg).\n  Add .webp onto the end.\n  Check this new path actually exists.\n\n\nThis can definitely be done more concisely, but I prioritised ease of reading / maintaining:\n\n{% assign path = include.path %}\n{% assign alt = include.alt | default: \"article\" %}\n\n{% assign image_parts = path | split: '.' %}\n{% assign extension_length = image_parts | last | size | plus: 1 %}\n{% assign base_path_length = path | size | minus: extension_length %}\n{% assign base_path = path | slice: 0, base_path_length %}\n\n{% assign webp_path = base_path | append: '.webp' %}\n{% assign webp_exists = site.static_files | where: \"path\", webp_path | first %}\n\n\nDisplaying WebP files\n\nFinally, we’re going to use Picture and source sets to let the browser determine if it can actually use the WebP we’re providing it. If not, it’ll use our original image instead:\n\n&lt;picture class=\"bg-img\"&gt;\n  {% if webp_exists %}\n  &lt;source type=\"image/webp\" srcset=\"{{ webp_path }}\" /&gt;\n  {% endif %}\n  &lt;img src=\"{{ path }}\" alt=\"Preview image of {{ alt | escape }}\" /&gt;\n&lt;/picture&gt;\n\n\nYou’ll notice we’re also using our alt parameter to set a somewhat useful alternative text for accessibility, although this could of course be made more specific if the banner image is important.\n\nExtra details\n\nCSS\n\nWhilst your template will likely differ, for my site this is the CSS that sets the size &amp; scaling of the image:\n\n.bg-img {\n  height: 180px;\n  border-radius: 0.17rem;\n  display: block;\n  overflow: hidden;\n}\n\n.bg-img img {\n  width: 100%;\n  height: 100%;\n  object-fit: cover;\n}\n\n\nWebP limitations\n\nI found some colours (especially dark orange) just wouldn’t render properly in WebP, regardless of quality settings. I strongly suspect this is an issue with the converter I’m using (since it has other long-standing broken functionality). It’s good enough for now, but may need replacing!\n\nConclusion\n\nUsing WebP drastically reduced the size of my site, and now it’s all automatic I won’t need to “fix” it again in the future. It’s long overdue, and I won’t be retroactively fixing past posts, but at least further posts will receive the benefits!\n\nIn terms of next steps, I’d like to add automatic banner image resizing, and be able to provide an alternate image for social media sharing. Neither of these is essential, and is arguably bloat, so perhaps not any time soon.\n\nEverything in this post is available as a Gist.\n"
    } ,
  
    {
      "tags"     : "GitHub, Education",
      "title"    : "My experience with the GitHub Foundations Certification process",
      "excerpt"  : "Did you know GitHub offer paid certifications? They do! The first of these is “GitHub Foundations”, offered for free to students, here’s my somewhat rocky experience of studying &amp; taking the exam.\n",
      "url"      : "/review-of-github-foundations-certification/",
      "date"     : "Nov 16, 2024",
      "content"  : "Did you know GitHub offer paid certifications? They do! The first of these is “GitHub Foundations”, offered for free to students, here’s my somewhat rocky experience of studying &amp; taking the exam.\n\nWant to skip directly to my study notes or the conclusion?\n\nOverview\n\nThe Foundations Certification came out earlier this year, and later on was made free for students with access to the GitHub Student Developer Pack. To quote GitHub’s docs, this certification covers “your understanding of the foundational topics and concepts of collaborating, contributing, and working on GitHub”, specifically:\n\n\n  Collaboration\n  GitHub products\n  Git basics\n  Working within GitHub repositories\n\n\nCompletion of the program rewards a Credly badge, as is typical of other online training courses.\n\nThis can be added to your LinkedIn:\n\n\n\nStudying\n\nAs a certification aimed at covering a wide area, some studying is required!\n\nSomewhat bizarrely, GitHub recommends multiple study guides on various platforms, namely:\n\n\n  DataCamp’s 4-course “Skill Track”\n  A LinkedIn 7-course “Learning Path”\n  A question-based study guide by a GitHub Developer Advocate. This is just a list of questions (e.g. “Describe branching”) with no answers or information provided.\n  Finally, a 16-module Microsoft “Learning Path”, which is what I used to study since Microsoft owns GitHub, this is recommended, and is text &amp; activity based, not video tutorials.\n\n\nThroughout my studying I made various notes along the way of bits from Microsoft’s training I might forget, feel free to fork the repo if you find it helpful.\n\nTraining contents\n\nI really, really enjoyed Microsoft’s Learning Path for this exam!\n\nThe typical format for a module is a few pages of text / diagrams to read, a 10-15 minute exercise performed on GitHub.com itself, then a (short, retakeable, multiple choice) knowledge check quiz. This adds up to around 30 minutes per module, so 8 hours for the entire learning path.\n\nModules\n\nWhilst the overall learning path wasn’t especially well organised, this was clearly because each module had been designed as an independent unit. For example, whilst the module “Contribute to an open-source project on GitHub” is clearly intended to come after the “Introduction to GitHub” module, it’s clearly written to also be suitable by itself.\n\nThis led to a small amount of going over topics again, but this was probably beneficial for the target audience of the course, since the minor parts of repeated content would typically be approached from a new perspective, and in a different level of detail. In general each module built on earlier modules’ teachings, so this is a minor complaint.\n\n\n\nExercises\n\nEasily the best feature of the training was the exercise repos on GitHub itself! Each of these (e.g. “Review pull requests”) requires forking a project, which triggers the README.md’s instructions to update in your fork of the project. Once the new instructions are followed, the README.md updates with extra information on what happened, and newer instructions to continue the exercise. Once this is repeated a few times, and the hands-on lessons have been learned, the exercise is complete.\n\nAll the exercises have the same getting started instructions:\n\n\n\nThis simple cycle, performed by GitHub Actions, excellently highlights how to use GitHub by forcing the user to actually perform the steps. It also gives a hint at how powerful GitHub is, and that it is far more than just a file storage or a collaboration tool. The exercises even cover useful yet rarely taught abilities like “connecting the dots” to hunt down a bug in a project using git blame.\n\nDespite knowing how these features work very well (I’ve likely reviewed 1000+ PRs!), I still completed the exercises because they were genuinely well written and fun. For a new user to GitHub, this hand-holding yet independent approach to getting the basics sorted would be unbelievably helpful.\n\nI’ll definitely be taking a look at all the “skills” training repos available and both trying some more myself and recommending them to more junior developers.\n\nExam\n\nSo I enjoyed the 7-8 hours of training, time to take the exam! Should be easy, right?\n\nWell, maybe if it went smoothly…\n\nAvailability\n\nI took this exam for free via GitHub Student Pack. There was an unfortunate issue on initial release where the certification was made free to everyone(!) and the program was paused, but as of the 11th November it’s available again for free.\n\nThis 2 month delay was a little annoying, but luckily I didn’t actually start studying until it was made available again. 2 months after incorrect implementation to get the vouchers working again seems a pretty long time, but it’s free so I can’t complain!\n\nRegistering\n\nWhen registering, the voucher to make the exam free was applied automatically, and there was a smooth handover between GitHub and the exam system (PSI exams).\n\nSome unusual additional information was required, such as a full home address without any explanation, and a request for my phone number. When I entered my number I was told my country wasn’t supported, but luckily I could skip this step! That same phone number was accepted later on as a contact number, so I’m not sure what changed.\n\nThe exam can be taken whenever you want, within 60 days of your registration. The scheduling confirmation email had some… odd parts (it was actually a 2-hour exam, and it had a name!), which was perhaps yet another warning that this process wasn’t perfect:\n\n\n  \n    Test: Exam Name\n    Duration: 11 minutes\n    Exam Availability: Anytime 24/7\n    Location: On Demand Testing\n  \n\n\nThe actual booking process was uneventful:\n\n\n\nTaking exam\n\nFinally, I went to start my exam. It required downloading and installing “PSI Bridge Secure Browser” which actually seemed shady enough that I double-checked the domain &amp; company were legitimate! They were, and I had no other options if I wanted the certification, so I installed the browser.\n\nSecurity check\n\nOnce installed, it somehow knew the exam I was taking and ran it’s “Security Check”.\n\nThis check was pretty obnoxious, I understand it’s to prevent cheating but what a pain it is! I had to unplug my 2nd monitor, close Chrome, Spotify, WhatsApp, VSCode, and even open up “Services” and disable a few Hyper-V and Nvidia processes. Again, I understand why I can’t have Chrome open, but this is a non-proctored exam and my phone is right in front of me, I suspect these controls work better in a classroom environment!\n\nStarting the exam immediately took me into what seemed like a post-exam survey, asking if I felt I’d had enough time, how I found the exam etc. These required answers were impossible to answer yet, so I just submitted neutral answers with the intention of revisiting them afterwards.\n\nSubmitting exam\n\nAfter an hour or so of answering every question (more on those later), I clicked submit and… received a fullscreen “Something went wrong” message. There was a “Details” button, so of course I clicked it to discover it was a TypeError around an undefined total!\n\n\n\nNot ideal. I tried every control I had available to me (changing colour scheme, contrast, navigating via different routes, refreshing the exam) and it would happen every time. I tried reopening the secure browser and luckily the answers saved, but same error. Restarted laptop, same error. Uh oh.\n\nCustomer support pain\n\nReady for a rant? Feel free to skip!\n\nI reached out to PSI’s support email and was told I had to talk to the technical team instead, via phone or live chat. Opening live chat led to a very frustrating conversation with an obviously script-following support agent who essentially ignored what I said unless it directly answered a question, despite me showing him the error at the very start!\n\nAfter 20 minutes of slow &amp; pointless back and forth, he asked if I’d restarted the secure browser. I had (and had told him in the first message), this apparently meant I had to contact GitHub! There were no more detailed instructions, he offered to give me a ticket number which was better than nothing, so… sure, off to GitHub we go.\n\nOver on GitHub I raised a support ticket, and had a far better experience. They replied within an hour that they are aware of the issue and are “coordinating with PSI” on it, with updates promised. 6 hours later, I received an email from Credly with my GitHub Foundation badge, I guess they managed to fix it!\n\n\n\nOverall PSI were very unhelpful, and I had to fend off multiple pointless suggestions (e.g. “Talk to your professor and ask to retake”) whilst also being pushed between support platforms (PSI email, PSI live chat, GitHub support) without any handover. This meant I had to explain my situation 3x, with only GitHub showing any empathy or responsibility.\n\nExam contents\n\nThe exam’s contents were surprising. Instead of being a knowledge check of GitHub basics, it was more of a trivia and obscure information check.\n\nI would estimate the exam consisted of:\n\n\n  30%: Things a developer would actually need to know, and should be tested on (what is a branch, what is a fork),\n  60%: Entirely pointless trivia that there is no value whatsoever in memorising, and can be easily looked up (how to access a setting, what view options are available for projects, features in GitHub paid plans).\n  5%: Debatable answers that have different answers for different teams (best practices, how to interact on open source repositories, PR behaviour).\n  5%: Incorrect, outdated, or unclear questions.\n\n\nFor example, one question asked “Which of the following can be performed within GitHub Mobile?”, with 5 possible answers. The correct answer was “Managing notifications from github.com”, and incorrect answers included “Managing enterprise and organization settings” but what is the point in knowing this? A user with the app installed can just use the website if they need to, and the app isn’t required anyway!\n\nAnother poor question asked where the 2FA settings can be found, with options including “Profile &gt; Account &gt; 2FA” and “Settings &gt; Password &amp; Authentication &gt; 2FA”. This is an essentially impossible question, since it’s a thing most users only configure occasionally, and the two answers are very similar regardless. Again, what’s the point in ever memorising the navigation path to 2FA? If you need to change it, you’ll click your user profile in the top right, and find a Settings-y option, and go from there.\n\nFinally, one particularly silly example. One question asked about “Private beta” and “Public beta” feature previews. This terminology was replaced a month ago, so there is no correct answer to the question!\n\nConclusion\n\n\n\nI really enjoyed the studying for the GitHub Foundations Certification exam, especially the hands-on exercises, even if the majority of it wasn’t new information. This was fully expected, since I’ve been a software engineer for 10 years so should know my way around GitHub! The training even gives a trophy, arguably almost as good as taking the actual exam:\n\n\n\nUnfortunately the exam’s tendency to test pointless trivia (not to mention fatal technical issues) was far less enjoyable.\n\nReputability\n\nI discovered after passing the exam that there’s many “practice exams” available online that essentially have very similar / identical questions and answers. I won’t link to them here since I’m pretty sure that’s essentially cheating, but it’s worth mentioning!\n\nDue to this, and the basic sounding “Foundations” certification, I’m not sure how much value this certification will actually add to a LinkedIn profile or Resume. I’d actually find completing Microsoft’s study guide training far more impressive (if the exercises are included), since it’s real, hands-on experience, in contrast to the exam’s trivia.\n\nOther certifications\n\nOverall I don’t think this certification is a good “advert” for GitHub’s certification program, at least for personal development. The study guides are essentially a more focused version of the existing documentation, with the exam more covering how well you can memorise minutia than actually use the tools.\n\nIf my employment heavily involved GitHub Actions, Administration, Advanced Security, or Copilot I might consider working through the study guides and getting corporate sponsorship (especially Actions), but as an Android Engineer they’re not worth it yet. A redditor has compared their experience taking all 5 exams.\n\nSummary\n\nI’d absolutely recommend the GitHub Foundations Certification to students since it’s completely free, or those with a corporate sponsor who will support their education. It teaches skills that almost every software engineer will need in their very first role.\n\nHowever, I wouldn’t recommend paying for it yourself, since arguably the most valuable part is the freely available training. I’d also not recommend it if you have a year or two of real world software engineering experience, instead it’s more useful as a “bridge” between a Computer Science degree education and actually using GitHub day-to-day.\n"
    } ,
  
    {
      "tags"     : "Android, Kotlin, Google",
      "title"    : "How to force update (& test) your Android app using Google's in-app update library",
      "excerpt"  : "Earlier this year, I needed to add the ability to force update users of an app. Whilst I’ve used custom solutions in the past, Google has a standardised “in-app updates” library that does all the essentials for you!\n",
      "url"      : "/googles-force-update-android-app-library/",
      "date"     : "Nov 9, 2024",
      "content"  : "Earlier this year, I needed to add the ability to force update users of an app. Whilst I’ve used custom solutions in the past, Google has a standardised “in-app updates” library that does all the essentials for you!\n\nThis article will assume Kotlin is used, if you require Java just remove the ktx dependency and adjust the provided code. All code used in this article is available as a GitHub gist.\n\nScenario\n\nThe ability to force a user to update their app is something that seems pointless… until it’s suddenly essential. This might be due to shutting down an outdated or insecure endpoint, a particularly bad bug in older versions, or even just the desire for customers to experience new features.\n\nRegardless of the exact reason for a future force update, it’s a core piece of functionality for any app from the very beginning.\n\nWhilst the in-app library does support optional (“Flexible”) updates, this article will just cover required (“Immediate”) updates. They’re self-explanatory, below are Google’s representative images:\n\n\n  \n    \n      Flexible / Optional update\n      Immediate / Required update\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nPreparing your app\n\nUnsurprisingly, the library needs to be added to your app! I’m using version catalogs and Kotlin DSL for Gradle, if you’re using Groovy or defining dependencies in a more classic way that approach works fine.\n\nDefining the dependency\n\nInside my libs.versions.toml, I add the latest version of the library &amp; ktx version (2.1.0 at time of writing):\n\n[versions]\nandroid-playAppUpdate = '2.1.0'\n\n[libraries]\nandroid-playAppUpdate = { module = \"com.google.android.play:app-update\", version.ref = \"android-playAppUpdate\" }\nandroid-playAppUpdateKtx = { module = \"com.google.android.play:app-update-ktx\", version.ref = \"android-playAppUpdate\" }\n\n\nUsing the dependency\n\nInside any module that you want to be able to force an update from, add the dependencies:\n\ndependencies {\n    implementation(libs.android.playAppUpdate)\n    implementation(libs.android.playAppUpdateKtx)\n}\n\n\nPreparing a wrapper\n\nWhilst there is documentation on calling the library, it’s hard to follow. All you’re actually doing is:\n\n\n  Checking if an update is available.\n  If it is, display the force update dialog.\n\n\nThat’s it! There’s complexity added due to the messy callback structure of the library, but this can all be abstracted away.\n\nMy wrapper is essentially the same as the official documentation, with a bit of function extracting etc for readability and simplicity. I’ll break down the component parts, feel free to just look at the full code.\n\nHandling the update dialog’s result\n\nSomewhat counterintuitively, we’ll look at the final step first.\n\nOnce the force update dialog has been shown, our app will receive a callback. We’ll just do basic logging for now in most scenarios, except if the user cancels / closes our dialog. This is a mandatory update, so we’ll pass in activity.finish() as a callback to close our app if this happens!\n\n    handleUpdateResult(result) {\n        activity.finish()\n    }\n\n    ...\n\n    private fun handleUpdateResult(result: ActivityResult, onUpdateDialogClose: () -&gt; Unit) {\n        when (result.resultCode) {\n            Activity.RESULT_OK -&gt; Timber.i(\"User has started mandatory update\")\n            Activity.RESULT_CANCELED -&gt; onUpdateDialogClose.invoke()\n            RESULT_IN_APP_UPDATE_FAILED -&gt; Timber.i(\"Mandatory update failed\")\n            else -&gt; Timber.i(\"Error whilst updating (${result.resultCode}): ${result.data?.data}\")\n        }\n    }\n\n\nDisplaying the force update dialog\n\nAgain, working backwards, we need to actually display the dialog assuming all conditions have been met.\n\nWe can just use a wrapper around the library’s startUpdateFlowForResult function, where activityResultLauncher is essentially a container with our handleUpdateResult from earlier.\n\n    private fun startForceUpdateFlow(\n        appUpdateInfo: AppUpdateInfo,\n        activityResultLauncher: ActivityResultLauncher&lt;IntentSenderRequest&gt;,\n        appUpdateManager: AppUpdateManager\n    ) {\n        appUpdateManager.startUpdateFlowForResult(\n            appUpdateInfo,\n            activityResultLauncher,\n            AppUpdateOptions.newBuilder(IMMEDIATE).build()\n        )\n    }\n\n\nDeciding if dialog should be shown\n\nFinally we come to the first step, determining whether the dialog actually needs displaying!\n\nThis is where the library really shines, boiling down all the complexity of checking if an update is required into a single function that returns a AppUpdateInfo. There’s a couple of helper functions to simplify the logic, and you should recognise our handleUpdateResult and startForceUpdateFlow functions.\n\nThe final core logic is very readable, simply “if update is in progress or an update is required, display the force update dialog”. Note that resuming an in progress update is the recommended behaviour.\n\n\n    fun forceUpdateIfNeeded(activity: ComponentActivity) {\n        // Must be declared before activity is resumed: https://stackoverflow.com/a/67582633/608312\n        val activityResult = activity.registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result -&gt;\n            handleUpdateResult(result) {\n                activity.finish()\n            }\n        }\n        val appUpdateManager = AppUpdateManagerFactory.create(activity)\n        val appUpdateInfoTask = appUpdateManager.appUpdateInfo\n\n        appUpdateInfoTask.addOnSuccessListener { updateInfo -&gt;\n            if (updateInfo.isUpdateInProgress() || updateInfo.isForceUpdateRequired()) {\n                startForceUpdateFlow(updateInfo, activityResult, appUpdateManager)\n            }\n        }\n    }\n\n    private fun AppUpdateInfo.isUpdateInProgress() =\n        updateAvailability() == DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS\n\n    private fun AppUpdateInfo.isForceUpdateRequired() =\n        updateAvailability() == UPDATE_AVAILABLE &amp;&amp; isUpdateTypeAllowed(IMMEDIATE)\n\n\nRemotely control the minimum version\n\nThe force update flow now works!\n\nHowever, we need the ability to remotely control which versions should be force updated. There are two built-in methods for controlling this, but we’ll use Firebase Remote Config instead (any remote value system works fine). The built-in options are:\n\n\n  Determine update behaviour based on how old the user’s app version is. This wasn’t suitable for me as I only wanted to force update in specific circumstances.\n  Set inAppUpdatePriority via the Google Play Developer API, then determine update behaviour in-app based on the priority value. This wasn’t suitable for me as I wanted a simpler way of setting the version to upgrade from, and for all the logic to be remote. Additionally, the value can only be set on initial rollout.\n\n\nSo, what will we use? Firebase Remote Config! Any system that lets you remotely serve a number will work, even if that’s something like checking a text file on your server. Remote Config is useful since it also lets us target specific values to subsets of our audience, for example only forcing users on bad version 100 to update to 101 whilst leaving users on good version 99 alone.\n\nIn this example, abTestManager is a wrapper within my app’s codebase, and not relevant or required.\n\nWe fetch a minimum allowed version code (e.g. 1000), and if the current app version (BuildConfig.VERSION_CODE) is higher or equal, none of the in-app update library code is called. This also adds a layer of safety from bugs in the library, as we can easily remotely disable the library’s ability to lock the user out.\n\n    fun forceUpdateIfNeeded(activity: ComponentActivity) {\n        val minimumAllowedVersion = abTestManager.remoteConfigLong(FirebaseRemoteConfigKeys.minimum_version)\n        if (BuildConfig.VERSION_CODE &gt;= minimumAllowedVersion) {\n            return\n        }\n\n        ...\n    }\n\n\nPutting it all together\n\nWe’re done!\n\nWe’ve checked the current version requires updating, we’ve used the library to check the update is available, then used the library to display a force update dialog, and listen to callbacks about the result.\n\nAgain, all code in this article is available as a GitHub Gist.\n\nCalling the wrapper\n\nOnce you’ve obtained an instance of your ForceUpdateHandler (I used dependency injection), the whole checking and updating process can be kicked off by calling it with an Activity or similar class (I used ComponentActivity):\n\nupdateHandler.forceUpdateIfNeeded(this)\n\n\nThis should be done as soon as possible in your app’s main / launcher Activity (e.g. in onCreate), wherever users start when opening the app. It’s also fine to call this from multiple Activities, e.g. if deep linked users go via a different Activity.\n\nNote that this must be called before your Activity’s onResume, as explained in this StackOverflow comment.\n\nTesting\n\nTo quote myself about testing on the PR to implement this feature:\n\n\n  Oh god. This took as long as the implementation!\n\n\nIt’s one of the hardest features I’ve ever had to test, due to the strict requirements on seeing the dialog, namely:\n\n\n  The app must be installed from the store.\n  A newer version of the app must be available to you on the store.\n  You must be using the device’s primary email (in my testing at least).\n  There are various device &amp; server caches that take hours to invisibly clear.\n  You cannot use an emulator (again, in my testing at least).\n\n\nSince we don’t want to actually deploy multiple new versions of our app to the store just to test a feature, we’ll be using the “Internal testing” track to give ourselves access to pre-release builds.\n\nThis internal sharing requirement is likely the cause of most of the complexity, since it requires bypassing all usual build preparation steps. In this scenario our live version code is 100, and we will be using 101 -&gt; 102 to test our updating.\n\nNote that whilst Google does have documentation for this process, it’s very limited and misses many of the steps / requirements.\n\nPreparing “old” app version\n\nFirst, a candidate to be force updated from needs to end up in Internal sharing!\n\n\n  Update your build with a higher version code (e.g. 101) than your current live version (e.g. 100).\n  Prepare a production keystore signed version of your app, it’s fine if you use Google Play Key Signing so long as your signing matches your usual production app process.\n  Upload this to the “Internal sharing” release track on Google Play Console, and make sure it is “released”.\n\n\nPreparing your device\n\nNext, we need to get this version onto our phone.\n\nOn your desktop:\n\n\n  Update the list of “Internal sharing” users to include your physical device’s primary email.\n  Find the internal testing opt-in link (will look something like https://play.google.com/apps/internaltest/123456).\n  Open this opt-in link in a browser with this same primary email logged in, and join internal testing (I had to use a desktop browser for this).\n\n\nOn your phone:\n\n\n  Go to the store listing for your app, and check it says “You’re an internal tester”.\n  Check the app version matches your test version (101), download and install the app.\n  Turn off automatic updates for this app (guide).\n\n\nIf that all went smoothly, you now have a test version on your device! There may be small delays at any stage whilst various caches update, techniques like restarting your phone may help.\n\nPreparing “new” app version\n\nNow we need a newer version to force update to.\n\n\n  Repeat all the steps in “Preparing old app version”, except with a higher version code (e.g. 102).\n  Open the system you’re using to control the minimum version (Firebase Remote Config in this example), and set the minimum version to the newly uploaded version (102).\n\n\nTriggering the force update\n\nSo, we now have version 101 on our device, version 102 on the store, and version 102 set as the minimum. Opening our now outdated app, we can see… nothing happens. Huh!?\n\nYou’ll now need to wait at least an hour or two for Firebase Remote Config cache to clear, Google Play cache to clear, and countless other delays along the way! It took around 4 hours of waiting for me, very painful when you’re trying to find out if a new feature works.\n\nIt’s fine to reopen the app during this wait, I didn’t find any way to “force” the latest version information to be updated. Whilst I tried closing my app, restarting the device, clearing the cache of Google Play Store and various other techniques they didn’t make any difference. I presume this is due to the delay being server side.\n\nAnyway, eventually you’ll open your app and… be prompted to update!\n\n\n\nNext steps\n\nOur app now has the ability to force update on demand, but that’s all. It can’t gently nudge to update, it can’t automatically prompt a user to update if their version is too old, or anything else more advanced. It also uses a default system dialog, which may not be desirable.\n\nFlexible updates\n\nThis is the obvious next step, prompting the user to update days before we force them.\n\nFlexible updates seem more complex, with the app itself being responsible for (optionally) restarting once the update is downloaded, and an expectation that the update prompting dialog does not show too frequently.\n\nThe optional update feature will likely work well with clientVersionStalenessDays, as simple logic such as prompting users when their version is &gt;7 days out of date would drastically reduce the users lingering on outdated versions. Performing a force update after another fixed interval is also an attractive proposition, especially as the risk of users getting “stuck” due to minimum SDK requirements etc is very minimal.\n\nCustom screens\n\nOf course, this is just a starting point. You might find the update prompting screen doesn’t fit your app’s tone of voice or marketing style, and want to build your own.\n\nThis can be done by replacing the contents of the startForceUpdateFlow function to display whatever blocking dialog you want, whilst being careful to ensure the user can’t “escape” by pressing back or using deep links.\n\nConclusion\n\nThe ability to force a user to update from a specific version to another is absolutely essential for any app. Nudging to update from outdated versions might be helpful, but getting the user off a bad version can avoid catastrophes.\n\nImplementing this using Google’s library allows skipping a lot of the manual work (e.g. how does the app know a new version is available?), and avoids having to keep an up-to-date record somewhere of which versions are acceptable.\n\nHowever, the trade-off for this is that the library’s somewhat roundabout set of functions needs to be used. This library is also rarely updated, with the last update 18 months before this article. Whilst this might mean it’s flawless, I suspect it actually means it’s mostly abandoned unless something major breaks! I’m certainly not holding out hope for usability improvements.\n\nAaaand one last time in case someone scrolled straight to the bottom: Here’s the GitHub Gist for the force update functionality.\n"
    } ,
  
    {
      "tags"     : "Android, GitHub, CI",
      "title"    : "A possible fix for intermittently hanging Android builds on GitHub",
      "excerpt"  : "I recently experienced an Android project’s GitHub build workflow sometimes taking 10 minutes… but sometimes freezing and eventually being killed after half hour by GitHub! The cause? Requesting too much RAM.\n",
      "url"      : "/gradle-build-freezing-on-github-ci/",
      "date"     : "Oct 23, 2024",
      "content"  : "I recently experienced an Android project’s GitHub build workflow sometimes taking 10 minutes… but sometimes freezing and eventually being killed after half hour by GitHub! The cause? Requesting too much RAM.\n\nScenario\n\nWe have a relatively simply GitHub workflow triggered by various events (PR raised, release triggered, etc), that just compiles a build, runs unit tests, and deploys a test build.\n\nTypically our build tasks take around 10 minutes, but seemingly at random builds would stop outputting anything for half hour, and eventually be killed by GitHub. This didn’t seem related to any code changes on the failed builds, and there were no actual errors, so diagnosing it was harder than expected.\n\nSymptoms\n\nInside the GitHub build job, the typically spammy lines of output will suddenly stop, and the build will stop all progress. This will persist for 25-30 minutes, when GitHub will likely cancel the build for high CPU &amp; RAM usage.\n\nOn the workflow page, the following errors are seen:\n\nAnnotations\n2 errors and 1 warning\n\nbuild: The runner has received a shutdown signal. This can happen when the runner service is stopped, or a manually started runner is canceled.\nbuild: The hosted runner encountered an error while running your job. (Error Type: Disconnect).\nbuild: Received request to deprovision: The request was cancelled by the remote provider.\n\n\n\n\nCause &amp; resolution\n\nThis happens when your Gradle build is allowed more RAM than GitHub’s runner has available, and a build happens to go over the limit.\n\nFor example, in our case the gradle.properties file previously specified 4GB of RAM:\n\norg.gradle.jvmargs=-Xmx4G\n\n\nHowever, it had been updated to -Xmx8G. This worked fine locally, and initially worked fine during CI builds too, but was the cause of problems a few days later!\n\nLooking at GitHub’s documentation for their runners, it turns out an ubuntu runner on a private repository only has 7GB of RAM &amp; 14GB of storage.\n\nWhilst I’ve used 8GB of RAM before, I only retroactively realised this was either for public repositories (with a 16GB limit), or macOS runners (with a 14GB limit)!\n\nNotes\n\nI was pretty surprised by the build process just freezing, I’d have assumed requesting more RAM than the runner has available would cause a pretty catastrophic failure. Diagnosing this issue took far longer than it should have, since some PRs old and new would work perfectly if they just happened to use less than 7GB RAM despite having 8GB available.\n\nOf course, the other solution is to pay for premium runners… but the GitHub-hosted runners are plenty for most use cases. I’ll try bumping up to 7GB RAM from 4GB next time I do CI maintenance, for now I’ve spent too much time staring at workflows today!\n\nAdditionally, the error messages currently give zero results(!) when Googled, so they’re included here in plaintext to help others:\n\n\n  build: The runner has received a shutdown signal. This can happen when the runner service is stopped, or a manually started runner is canceled.\n  build: The hosted runner encountered an error while running your job. (Error Type: Disconnect).\n  build: Received request to deprovision: The request was cancelled by the remote provider.\n\n"
    } ,
  
    {
      "tags"     : "Python, Archive.org, StumbleUpon, BeautifulSoup",
      "title"    : "How to bulk download all past versions of a webpage, parse the data in Python, and save to CSV",
      "excerpt"  : "I recently needed to download hundreds of past versions of a StumbleUpon webpage, parse the HTML, and output the data into a CSV for further analysis. Here’s how to do it!\n",
      "url"      : "/bulk-downloading-website-history-and-parsing/",
      "date"     : "Oct 19, 2024",
      "content"  : "I recently needed to download hundreds of past versions of a StumbleUpon webpage, parse the HTML, and output the data into a CSV for further analysis. Here’s how to do it!\n\nWhat’s the goal?\n\nFor an upcoming project, I needed to extract as much historical data (2009-2012) from StumbleUpon as possible, and output it into a CSV. The obvious approach to this is using Archive.org’s Wayback Machine to download all versions of “top posts” pages, then some Python processing to extract data from the downloaded pages.\n\nTo summarise, my input is a target URL, my desired output is a CSV with information extracted from the multiple results contained within each historical version of the URL’s contents.\n\nIf you just want to see the code, here’s a GitHub gist of the Python scripts &amp; batch command, plus a full GitHub repo including results.\n\nWhat’s the plan?\n\nAssuming I already have a URL I wish to extract from, my plan is:\n\n\n  Step 1: Download every version of the URL available.\n  Step 2: Parse the downloaded pages into a CSV.\n  Step 3: Tidy up the resulting data.\n\n\nStep 0: Prepare environment\n\nWe’re going to be using Python to download the pages and parse the downloaded data, so first we need a decent environment for it!\n\nYou can of course skip the Python installing step if you already have it configured, you will however need to install the libraries this guide uses.\n\nInstalling Python\n\nI installed it on my Windows machine without any problems, but make sure to follow any platform-specific instructions.\n\n\n  Download the latest version from Python.org.\n  Install with mostly default options, plus:\n    \n      The “Optional feature” pip (to install packages).\n      The “Advanced option” Add Python to environment variables (to allow command line usage).\n    \n  \n\n\nI initially installed Python without either of these features, and had to rerun the installer and select “Modify”. Oops.\n\n\n  \n    \n      Optional features\n      Advanced options\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nInstalling libraries\n\nWe’re going to be using 4 libraries for this project:\n\n\n  waybackpack: To automate the Wayback Machine downloading process.\n  beautifulsoup4: To parse &amp; extract data from the downloaded HTML.\n  lxml: Adds a (generally) faster parser that beautifulsoup4 can use (more info).\n  pandas: To deduplicate the CSV output.\n\n\nLuckily, we can install all of these at once in a single command in Command Prompt:\n\npip install waybackpack beautifulsoup4 lxml pandas\n\n\nAfter a few minutes of installing, we’re ready to go!\n\nStep 1: Downloading all versions\n\nAs mentioned, we’ll be using waybackpack to download every version of our target URL(s).\n\nPreparing download script\n\nWhilst the most basic usage is just waybackpack {url} -d {destination}, There’s quite a few config options available for this utility that drastically improve behaviour. Here’s what I ended up with:\n\nwaybackpack ^\nhttp://www.stumbleupon.com/discover/toprated/ ^\n-d \"/Projects/StumbleUpon-extract/data-raw\" ^\n--from-date 20091001 ^\n--to-date 20120318 ^\n--raw ^\n--no-clobber ^\n--delay-retry 2 ^\n--max-retries 10 ^\n--ignore-errors ^\n--user-agent \"waybackpack {myemail}\"\n\n\nSo, what does it all do?\n\n\n  The ^ at the end of each line lets me copy &amp; paste into the command prompt as a multi-line command for ease of reading.\n  from-date and to-date need customising based on your URL. For my target URL, I noticed the valid archives are only between October 2009 and March 2012, after which all the requests fail. Adding these fields avoids pointlessly fetching a few years worth of error / redirect pages!\n  raw fetches the actual source content, without the Wayback Machine URL rewriting, added JavaScript, or any other changes. This is useful since we want the original data, not to actually browse the pages.\n  no-clobber skips trying to fetch any files that are already downloaded. This ensures running the same command again will only try to fetch the failed pages, not all the successful ones.\n  delay-retry and max-retries handle the retry delay (in seconds) and how many tries to make before giving up. Archive.org was fairly unreliable at time of writing, so connection errors were quite common. Running the entire command again a few minutes later typically resolved the problem.\n  Whilst network / server errors are handled already, ignore-errors ensures errors within the code don’t stop the whole extract process.\n  user-agent contains the tool we’re using, and my email, as a courtesy to Wayback Machine in case the tool is doing something wrong with their API, or they need to contact me.\n\n\nRunning download script\n\nCopying and pasting the whole command into Command Prompt will start the download process, with each archive taking under 1 second for successful fetches, and up to 20 seconds for unsuccessful fetches. Total time is typically 3-4 seconds per copy.\n\nNotes:\n\n\n  The files will end up in the specified destination in the format /timestamp/url, creating any necessary folders. For example, http://www.stumbleupon.com/discover/toprated/ will be saved in /20120101165409/www.stumbleupon.com/discover/toprated/index.html.\n  Passing a URL ending in / will result in index.html, otherwise the filename will be the path (e.g. toprated with no extension).\n  It’s likely a few fetches will fail (with max retries) on first attempt, so I’d recommend running the command a couple more times until the only failures are HTTP status code: 301. Each retry should try fewer and fewer URLs due to the no-clobber option!\n\n\n\n  \n    \n      Example output\n      Poor connection output\n      Downloaded files\n    \n  \n  \n    \n      \n      \n      \n    \n  \n\n\nStep 2: Parsing data into CSV\n\nThis step is going to be relatively specific to my use case; extracting links from archived StumbleUpon pages. However, the overall approach is applicable to any data extracting needs, with just the specific fields needing changes.\n\nRequirements\n\nFor my scenario, the requirements were:\n\n\n  Parse each downloaded HTML file, and extract the 10 links included.\n  For each link, extract as much metadata as possible (e.g. views, title, URL).\n  Output the extracted metadata into a CSV for further analysis.\n  Automate the process as much as possible!\n\n\nBefore diving into the solution, it might be helpful to look at sample inputs and outputs to clarify the objectives:\n\n\n  Sample input HTML, containing 10x links (sample) plus lots of irrelevant data.\n  Sample output in CSV format (note GitHub will autoformat into a table for readability).\n\n\nWe’ll run our script with python extract_stumbleupon_metadata.py, which will extract all the metadata from each file:\n\nPS C:\\Users\\jake_\\Documents\\Projects\\StumbleUpon-extract&gt; python .\\extract_stumbleupon_metadata.py\n2024-10-19 22:24:47: Processed 10 items from #1: data-raw\\20091010195948\\www.stumbleupon.com\\discover\\bizarre\\index.html\n2024-10-19 22:24:47: Processed 10 items from #2: data-raw\\20091010200605\\www.stumbleupon.com\\discover\\toprated\\index.html\n2024-10-19 22:24:47: Processed 10 items from #3: data-raw\\20091011005504\\www.stumbleupon.com\\discover\\health\\index.html\n2024-10-19 22:24:47: Processed 10 items from #4: data-raw\\20091011005516\\www.stumbleupon.com\\discover\\movies\\index.html\n2024-10-19 22:24:47: Processed 10 items from #5: data-raw\\20091011005527\\www.stumbleupon.com\\discover\\travel\\index.html\n2024-10-19 22:24:47: Processed 10 items from #6: data-raw\\20091011105316\\www.stumbleupon.com\\discover\\news\\index.html\n\n\nScript overview\n\nThe Python script is on GitHub, although it’s a little messy as it’s specific to this project!\n\nBefore diving too deep into a line-by-line analysis, here’s how the script works:\n\n\n  Step 2a: Define a few parameters around input and output, and check the local environment.\n  Step 2b: Define a extract_metadata function that opens the HTML file passed to it, parses all the links, and returns a list of metadata objects (each of which is a CSV line).\n  Step 2c: Find every downloaded HTML file, pass them to extract_metadata, and save all the metadata into the output_csv.\n\n\nStep 2a: Overall setup\n\nTiny bit of simple setup, before the useful functionality starts:\n\n\n  The root_dir and output_csv variables let the script know where the HTML input files and CSV output file should be.\n  max_files is used to aid testing, to try parsing 1-2 files initially.\n  stumbleupon_prefix is used for extracting the “real” URLs.\n  Finally, os.makedirs ensures the output CSV folder exists and is accessible.\n\n\nimport os\nimport csv\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nfrom urllib.parse import unquote\n\nroot_dir = r'data-raw'\nmax_files = 10\nstumbleupon_prefix = 'http://www.stumbleupon.com/url/'\noutput_csv = 'data-parsed/parsed.csv'\n\nos.makedirs(os.path.dirname(output_csv), exist_ok=True)\n\n\nStep 2b: Metadata extracting\n\nWhilst there’s quite a big chunk of code inside extract_metadata, none of it is actually very complicated or clever!\n\nAll we’re doing is finding every listLi element, pulling out data within it, and adding it all to our metadata dictionary. These are then all collated and returned to the caller. The desired output is similar to:\n\n\"id\",\"url\",\"title\",\"review_count\",\"view_count\",\"date\",\"user_id\",\"user_name\",\"source\"\n\"1x8XK0\",\"https://www.typographyserved.com/Gallery/August-2009/282018\",\"August 2009 :: Typography Served\",14,24224,20091011113141,2342625,\"Lyze\",\"toprated\"\n\"2PAkaD\",\"https://murderburger.wordpress.com/2009/05/11/swine-flu-7-dead-6-5-billion-not-dead/\",\"Swine Flu. 7 dead. 6.5 billion not dead.  &amp; Murder Burger et al.\",33,40291,20091011113141,7259679,\"growmap\",\"toprated\"\n\n\nAnd the Python function to do this is:\n\ndef extract_metadata(file_path):\n    with open(file_path, 'r', encoding='utf-8', errors='ignore') as file:\n        content = file.read()\n        soup = BeautifulSoup(content, 'lxml')\n        list_items = soup.find_all(class_='listLi')\n        metadata_list = []\n        for item in list_items:\n            user = item.find(class_='avatar')\n            reviews = item.find(class_='showReview') or item.find(class_='showStumble')\n            raw_url = f'https://{reviews.find(\"a\")[\"href\"][len(stumbleupon_prefix):]}'\n            views = item.find(class_='views')\n\n            # Assumes relative path `data-raw\\20091011113141\\www.stumbleupon.com\\discover\\toprated\\index.html`\n            path_parts = file_path.split(os.sep)\n\n            metadata = {\n                'id': f\"{item.find('var')['class'][0]}_{item.find('var')['id']}\",\n                'url': unquote(unquote(raw_url)),\n                'title': item.find(\"span\", class_='img').find(\"img\")[\"alt\"].strip(),\n                'review_count': int(''.join(filter(str.isdigit, reviews.find('a').get_text(strip=True).split()[0]))),\n                'view_count': int(''.join(filter(str.isdigit, views.find('a')['title'].split()[0]))),\n                'date': int(path_parts[-5]),\n                'user_id': int(user['id']) if user else -1,\n                'user_name': user['title'] if user else 'Unavailable',\n                'source': path_parts[-2]\n            }\n            metadata_list.append(metadata)\n        return metadata_list\n\n\nBefore looking at a detailed data extraction example, it’s worth highlighting that the downloaded data is a little unreliable / messy. As such, a few notes:\n\n\n  The metadata id is a combination of the post’s CSS class and the id, since the class names aren’t necessarily unique, and id is sometimes missing.\n  Sometimes the user is empty, so we need default values.\n  We double unquote the url to get a “real” URL out.\n  Some pages have the URL as the title. This is not an error in the data, it’s on the site too (last result)!\n\n\nExtraction step-by-step\n\nThe parsing can seem complicated, but they all just require careful reading. Looking at an example listLi element, we have this source HTML:\n\n&lt;p class=\"showReview\"&gt;\n  &lt;a\n    href=\"http://www.stumbleupon.com/url/sciencehax.com/2010/01/beautiful-home-built-from-recycled-materials/\"\n    &gt;46 reviews&lt;/a\n  &gt;\n&lt;/p&gt;\n\n\nWe first need to actually find this element, it is usually the element with class showReview but can be showStumble in some scenarios. This can be expressed as:\n\nitem.find(class_='showReview') or item.find(class_='showStumble')\n\n\nNow we have the reviews object, we can chain a few Python functions on it:\n\nint(''.join(filter(str.isdigit, reviews.find('a').get_text(strip=True).split()[0])))\n\n\nHow does this work? Well, from the inside out:\n\n\n  First we find the a element (reviews.find('a')) and get the link text (get_text), giving us 46 reviews.\n  Next, we split this into 46 and reviews and take the first string (with .split()[0]).\n  Now, we make sure this is a simple number (e.g. 12,345 to 12345) by removing any non-numerical characters (filter(str.isdigit, \"46\")).\n  This gives us the array [\"4\", \"6\"], so we use ''.join to put it back into a single string.\n  Finally, int() wraps everything, as we want a numerical output (to avoid any quotation marks in the CSV).\n\n\nHopefully that example highlights how seemingly complex parsing is pretty straightforward, even for other fields that are fetched from the file’s path itself (path_parts).\n\nStep 2c: File input &amp; output\n\nAs a reminder, our goal is to find every available .html or extensionless file, parse them with extract_metadata, then save the extracted data into a CSV.\n\nWe’ve got a bit of extra logic to output the CSV headers, and allow limiting the number of files to parse, as well as outputting timestamps for logging purposes.\n\nwith open(output_csv, 'w', newline='', encoding='utf-8') as csvfile:\n    fieldnames = ['id', 'url', 'title', 'review_count', 'view_count', 'date', 'user_id', 'user_name', 'source']\n    writer = csv.DictWriter(csvfile, fieldnames=fieldnames, quoting=csv.QUOTE_NONNUMERIC)\n\n    writer.writeheader()\n\n    # Traverse directories and process HTML files\n    file_count = 0\n    for subdir, _, files in os.walk(root_dir):\n        for file in files:\n            if file_count &gt;= max_files:\n                break\n            file_path = os.path.join(subdir, file)\n            # Check if the file has no extension or has an .html extension\n            if not os.path.splitext(file)[1] or file.endswith('.html'):\n                metadata_list = extract_metadata(file_path)\n                for data in metadata_list:\n                    writer.writerow(data)\n                file_count += 1\n                current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n                print(f\"{current_time}: Processed {len(metadata_list)} items from #{file_count}: {file_path}\")\n        if file_count &gt;= max_files:\n            break\n\n\nAgain, nothing complicated here, it’s just a big old nested for loop looking at every file in the input directory!\n\nStep 3: Sanitising the data\n\nSince we downloaded every toprated page version available on the Wayback Machine, some of the data will actually overlap! This page only updates slowly, so there’ll be a few overlapping items even with archives 24 hours apart.\n\nAdditionally, I actually downloaded content from /toprated/, /animation/, /arts/, totalling over 30 URLs (full list)! Downloading all copies of all these URLs resulted in 1,545 HTML files (/data-raw/), which contained a total of 13,365 items.\n\nHowever, we know we have duplicates. This problem is made much worse when fetching data from category pages, since obviously popular content in a category will end up on the overall toprated screen. Uh oh.\n\nDeduplication\n\nLuckily, we used a sensible id earlier that doesn’t include anything date-related!\n\nAs such, we can just deduplicate our CSV by this ID. We should take the last instance of an ID, since all of our data is automatically date sorted (due to the download tool using date folders).\n\nUsing the data analysis tool pandas, we can create a tiny clean_stumbleupon_metadata.py that does exactly what we want:\n\nimport pandas as pd\nimport csv\n\ndf = pd.read_csv('data-parsed/parsed.csv')\ndf = df.drop_duplicates(subset='id', keep='last')\ndf.to_csv('data-parsed/parsed-cleaned.csv', index=False, quoting=csv.QUOTE_NONNUMERIC)\n\n\nRunning this creates a new, deduplicated parsed-cleaned.csv containing just 4,443 rows from the original 13,365. Perfect!\n\nThis data is also available as a Google Sheet.\n\n\n\nConclusion\n\nSo, to summarise what we’ve done, in terms of our original plan:\n\n\n  Step 1: We ran waybackpack wih our target URL, and ended up with hundreds of html files.\n  Step 2: Next, we ran our extract_stumbleupon_metadata.py script, a few minutes later ending up with a CSV full of all extracted data.\n  Step 3: Finally, we ran clean_stumbleupon_metadata.py to remove duplicated data.\n\n\nThis approach can be adapted for use on any URL or data format, and whilst none of it is very complicated, it’s my first time doing anything notable in Python. Lots of things learned!\n\nThe final CSV will be used for an upcoming post on Internet History. Aaaand as one final reminder, all code and data from this article is available on GitHub.\n"
    } ,
  
    {
      "tags"     : "Liquid, Jekyll, Web",
      "title"    : "Building a Jekyll / Liquid calendar with custom events",
      "excerpt"  : "I recently created a full-year calendar displaying custom events from Jekyll posts in the Liquid language, here’s how it works and how to use it!\n",
      "url"      : "/jekyll-calendar-custom-events/",
      "date"     : "Oct 11, 2024",
      "content"  : "I recently created a full-year calendar displaying custom events from Jekyll posts in the Liquid language, here’s how it works and how to use it!\n\nBefore diving into how the calendar works, here’s a few useful links:\n\n\n  A live demo of the calendar on my Internet History site.\n  All code is available as a GitHub Gist, or in a merge commit to my minimaJake Jekyll theme.\n  The latest version of the calendar, which might have a few post-release improvements.\n\n\nWhat can the calendar do?\n\nWell, all the basic features you’d expect of a calendar:\n\n\n  Display every day in an arbitrary year, with months / days of week.\n  Add multiple arbitrary events to days from any site post.\n  Clicking a day with events to view more information, e.g. how many years ago an event on that day happened, and linking to the post the event is defined on.\n\n\nHere are some screenshots:\n\n\n  \n    \n      Dark\n      Light\n      Mobile\n    \n  \n  \n    \n      \n      \n      \n    \n  \n\n\nHow can I add it to my Jekyll site?\n\nThe calendar is just a Liquid script with a little CSS / HTML / JavaScript to improve functionality / UI, so:\n\n\n  Copy calendar.html into any HTML or Markdown page on your Jekyll site.\n    \n      Note: I copied it to _includes/custom/calendar.html and used {% include custom/calendar.html %} on a page.\n    \n  \n  Copy styles.css to your site’s CSS file, replacing #ca644e with your site’s accent colour.\n  Add a dates list to a post (example), containing objects with a YYYY-MM-DD date and a title.\n  Start your site, visit your new calendar!\n\n\nHow can I customise the calendar?\n\nObviously basic stylistic changes can be made in the CSS, all the classes are self-explanatory so shouldn’t be any issues. I’d recommend not changing the display or grid-template-columns to avoid chaos!\n\nHowever, you’re more likely to want to change the behaviour. Liquid can be unintuitive, and whilst I’ll run through the code in detail, here’s how to change common features:\n\nOnly display current year\n\nFor my use case, I wanted to display events in any year on a specified day, however a calendar is usually only for a specific year!\n\nTo change this:\n\n\n  Replace assign current_year = 'now' | date: '%Y' with assign current_year = 2024 (or the year of your choice).\n  Change both instances of %m-%d to %Y-%m-%d, so the year is included when finding events.\n  The “Years ago” text logic is now meaningless, so you can remove lines 34-40, and remove append: years_ago_text |.\n\n\nChanging popup contents\n\n\n  To change the per-event text, just modify line 41’s appends with whatever text you want.\n  To change what the popup dialog looks like, or it’s behaviour, the browser’s default behaviour is used so you’ll need new CSS rules / JavaScript.\n\n\nUsing post publish dates\n\nWhilst I wanted to define custom events for my calendar, you might want to just use post dates. This can be done by:\n\n\n  Removing the lines with for event in post.dates (line 32) and endfor (line 44).\n  Changing both event.dates to post.date.\n\n\nHow does it work?\n\nThese details are mostly to stop me forgetting in a few months, but they may help you make changes to the code too!\n\nAs a reminder, all the code is in a GitHub Gist: https://gist.github.com/JakeSteam/d7f7c681412989bb3c173cc850b756f9\n\nDisplaying a month\n\nDisplaying all the days in a month correctly aligned to the days of the week grid is easily the hardest part of a calendar, and luckily someone already solved it for me!\n\nSpecifically, this post (in Russian) by Mikhail Yudin was used as a starting point, with some adaptations. Essentially, to ensure we output placeholder days from the previous month, we:\n\n\n  Start 7 days before the start of the month (-7..30), and loop through each day by building a day_timestamp using the month_start_timestamp and current day (i).\n  For each day, if we haven’t found the first relevant day yet (first_day_found), skip the day without outputting (continue) until the current day is Monday.\n  Now we need to output placeholder days for the row until the month actually starts, this is done with if month_str == month_number … output day span … else … output empty span.\n  To output a day’s events, we loop through every object in every post’s dates object.\n  For each event, we add the HTML output to events, which is added to the page’s HTML itself as a data-events attribute on the day’s span.\n\n\nStyling with CSS:\n\n\n  Using CSS, lay out all the days in calendar-grid in a grid with 7 columns and some spacing (display: grid; grid-template-columns: repeat(7, 2rem);).\n  Similarly, lay out the months themselves in a grid that reacts to screen width (grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));).\n  Finally, add some nice touches like borders, a pointer for clickable days, colours, padding, etc.\n\n\nDone!\n\nLooping through every event on every post for every day is absurdly inefficient (e.g. 10 posts with 10 events each calculated for every day = 10*10*365 = 36,500 checks total), however since this is all done once at compile time… I don’t really mind.\n\nThe page will always load in milliseconds even with thousands of events / posts. I had a brief try at implementing some sort of events hashmap to optimise the lookups, but Liquid really isn’t made for this kind of programming! The dumb, simple solution is good enough.\n\nDisplaying all months\n\nLiterally just repeat the month displaying {% for month in (1..12) %}, plus outputting the month name (%B)!\n\nDisplaying a dialog\n\nShoutout to HTML for now including a native dialog element! This element does all the hard work of fading the background, displaying a dialog in the middle of the screen, and even has a special syntax to close it without any JavaScript:\n\n&lt;form method=\"dialog\"&gt;\n  &lt;button autofocus&gt;Close&lt;/button&gt;\n&lt;/form&gt;\n\n\nSome JavaScript is still needed however, to dynamically populate this dialog. When the page loads, we:\n\n\n  Select all days with events (const eventDays = document.querySelectorAll('.calendar-event');)\n  For each one, add a click listener.\n  On click, set the dialog’s eventContent to the contents of the clicked day’s data-events attribute, and showModal() to display it.\n\n\nDisplaying years since\n\nAnother simple one, just subtract the event’s year (%Y) from the current year, and display “This year” if this is 0, otherwise “_ years ago”.\n\nConclusion\n\nThis was a fun mini-project, and I’m looking forward to slowly filling up my Internet History calendar with notable dates! It was also good to work in Liquid again, even if syntax highlighting and autoformatting is pretty unreliable.\n\nI’m extremely impressed with the month outputting solution that formed the core of this calendar, the day skipping approach is very creative. Hopefully I need to implement a calendar in another language soon, so I can perform this magic trick for someone!\n\nIn terms of additional features, I’m not sure there’s anything notable I’d like to add. Some slightly nicer styling, or more efficient event collating perhaps, none of this is essential though. If you end up using the calendar and have ideas, let me know and I’ll probably give implementing them a go.\n"
    } ,
  
    {
      "tags"     : "Post-mortem, Next.js, Web, TypeScript",
      "title"    : "A post-mortem of \"BountyHour\", an unfinished microcontracting marketplace using Next.js, tRPC, and Prisma",
      "excerpt"  : "Like every developer, I have plenty of ideas, most of which never get beyond the planning stage! BountyHour was one of them that made it into proper development, and was then abandoned. So, what happened?\n",
      "url"      : "/bountyhour-microcontracting-postmortem/",
      "date"     : "Oct 5, 2024",
      "content"  : "Like every developer, I have plenty of ideas, most of which never get beyond the planning stage! BountyHour was one of them that made it into proper development, and was then abandoned. So, what happened?\n\nLinks\n\n\n  Planning documents (cited frequently in this article)\n  Codebase\n  Placeholder site (expires soon, apologies if someone else reuses it!)\n\n\nWhat was BountyHour?\n\nTo quote the now public planning docs:\n\n\n  Bounty Hour is a micro-contracting marketplace, loosely based on the “bug bounty” system.\n\n  Development teams who are unable to solve an issue (bug / issue / feature) and require a specialist can submit a bounty, that specialists can pick up.\n\n  The bounty is only paid out when (or if) the work is completed, and may be attempted by multiple specialists. Each specialist only has 24hr to complete a bounty, after which it is freed up for another.\n\n\nEssentially, it was intended to be a way for highly skilled software engineers to use some of their spare time to pick up time-sensitive, extremely challenging bounties.\n\nTarget audience\n\nA key question for any new project is “who is it for?”. Luckily, since I could potentially be both a bounty hunter &amp; poster, writing the pitch was easy!\n\nBounty hunters\n\nAs a software engineer myself, making a service that I wish existed was essential. I want to challenge myself in my spare time, and getting paid for it would be a nice bonus! As such, the “sales pitch” for bounty-hunting developers was simple:\n\n\n  The vast majority of your job is probably building large new features or tidying up code. You might go entire weeks without actually doing anything new or challenging yourself.\n\n  Why not spend an hour of your time to do something challenging, and get paid extra for it?\n\n\nPeople already do this for internet points on StackOverflow, doing essentially the same for pay should be an easy sell.\n\nBounty posters\n\nThe other side of the equation is those posting the bounties. This was envisioned as software teams (or their managers) that are irredeemably stuck on a problem. I hadn’t decided if I’d encourage employees to outsource their own work, as whilst this would drastically increase the number of bounties… it would likely break contracts!\n\n\n  Got a problem that’s been plaguing you for months, and nobody on the team seems able to solve it? Instead of hiring a contractor for a week and hoping you get lucky, put out a BountyHour. Review verified experts, choose your requirements, and post. No fix, no fee.\n\n\nInvestors / employees\n\nFinally, assuming the original business plan takes off and bounties are being posted &amp; solved, the eventual expansion was considered somewhat. As a “middleman”, similar to eBay for sales, the overheads should be relatively low. Additionally, software engineers with time / money to spare are likely a very appealing advertising target!\n\n\n  Low risk, as BH is just a middleman. Low overheads, high scalability. Ability to cross-sell / upsell easily to high-wealth individuals.\n\n\nUnique offering\n\nSince almost every tech idea pitching for investment will be asked variations of “OK, but what makes this idea different?”, I made a few initial notes:\n\n\n  \n    Scope: BountyHour is only for solving bugs, crashes, and problems. It’s not for general software development.\n    Private: Bounties have public metadata, but any detailed data is only shown to potential hunters, and code is only shown to an assigned hunter.\n    All in one: Code management, communications, and payments all within the platform.\n    Hunters: Instead of independent freelancers trying to earn a living, BountyHour mostly uses already employed people looking for an extra challenge.\n  \n\n\nFeatures\n\nAs with any personal project, the potential scope creep was giant. In addition to the basic idea of listing &amp; claiming bounties, BountyHour would have had:\n\n\n  Escrow payments, e.g. taking payment upfront, handling tax implications for all involved, adding ability to donate bounties to charity.\n  Company verification, e.g. BountyHunters connecting their LinkedIn with verified emails allowing them to be listed automatically as “Mobile Engineer with 3 years Meta experience” etc.\n  Bounty types, e.g. a bounty might be a “snippet”, a GitHub repo (fully integrated with BountyHour), Dropbox, or a plain old zip file.\n  Bounty failing, e.g. expiry, extension requesting, ability to add notes to failed bounties for the next attempter.\n  Bonuses, e.g. a 20% bonus payment if completed within 3 hours.\n  Feedback, similar to eBay, e.g. communication, code quality, etc.\n\n\nHow much progress was made?\n\nEssentially:\n\n\n  Authentication: The ability to signup &amp; login (via email, LinkedIn, or GitHub).\n  Profile Settings: The ability to customise your name, privacy settings, timezone, etc.\n  Appearance Settings: Full light &amp; dark theme support, plus full responsiveness on all pages.\n  View Bounties: An absurdly customisable list of assigned / created bounties.\n\n\nI’ll go into these all briefly, as a reminder all the source code is in the repo.\n\nAuthentication\n\nThis uses NextAuth.js to handle authenticating via GitHub (useful for code management), LinkedIn (useful for employer information), or email. Magic links are used for email, with Mailtrap suitable for my very limited dev usage.\n\nAuthentication is famously hard, and honestly I’m pretty happy with my final result. It did exactly what I wanted, for free, with minimal code to maintain. There were some… interesting headaches around the OAuth implementation, but it got there in the end!\n\n\n  \n    \n      Login\n      Login (mobile)\n      Login (mobile, light)\n    \n  \n  \n    \n      \n      \n      \n    \n  \n\n\nSettings\n\nI spent absurdly long on the profile editing, in pursuit of a perfect form. Realistically this obsession to detail might have contributed to the project’s demise, but I’m still extremely proud of all the features included in my 2nd-ever form!\n\n\n  Client-side data validation, using the same schema definition(!) as the server, via “Zod”.\n  Monitoring of form “dirtiness”, and only enabling the save button if there is new data. Additionally, only changed data is submitted.\n  Per-field error handling, both client and server-side.\n  Dynamically populated fields &amp; tooltips.\n\n\nAll of this isn’t ground-breaking, but it is above the usual standard you’d expect in a web form. It’s definitely far above the MVP standard it perhaps should have been built to!\n\nDark mode was also implemented “perfectly” (well, in my eyes), with defaulting to system preferences and the ability to override from any page. This page was of course as responsive as all others.\n\n\n  \n    \n      Profile information\n      Saving profile\n      Appearance\n    \n  \n  \n    \n      \n      \n      \n    \n  \n\n\nBounties\n\nAnother case of “pursuing perfection at all costs”, this table listed all bounties created or assigned to the user. However, again, it had enough features to make it extremely high quality:\n\n\n  Sort by any field\n  Filter by any field, including Enum (status) or Date-based (updated, e.g. “in last week”)\n  Hide fields\n  Fulltext search fields\n  Pagination, including customisable rows per page.\n\n\nWhilst these features were primarily implemented already by shadcn-ui, putting all the pieces together in a generic way, only requiring the data and headers to be passed in by the developer, was tricky!\n\n\n\nWhat tech did it use?\n\nSince BountyHour used T3 as a starting point, all the tech choices were pretty standard:\n\n\n  TypeScript (Language)\n  Next.js (Framework)\n  NextAuth.js (Authentication)\n  Prisma (ORM)\n  Tailwind (CSS)\n  tRPC (API)\n\n\nThis was my first time using any of these, so it took a while to figure out exactly which bit did what! However, by the end of it I was relatively confident in at least understanding an implementation of these, and making minor changes.\n\nI’ve written about this in detail before, but having someone more knowledgeable provide a solid starting point was the only way this project made any progress at all. The choices all seemed to align with my priorities, and if I’d had to pick each library by myself it would have taken months to even make the first commit!\n\nWhy was it abandoned?\n\nScope\n\nBountyHour is too big. Realistically it requires a whole team to even get started (especially due to the legal, financial, and customer support resources required), with no possibility of starting small then “scaling up” (since the core functionality requires all the complexity).\n\nWhilst I do still think the idea has massive potential, an Android engineer with a passing interest in web who just about knows the basics is not the guy to realise it! A better match would be an experienced web engineer who specifically has worked with payments, chat, and code management before.\n\nThere’s also the consideration that all of the technical parts I struggle with (e.g. actually building messaging, payments, etc) aren’t hard or novel, they’re just new to me. As such, it’s entirely possible another company (or individual) could have the same idea, and be up and running months before me, with a higher quality product.\n\nExpertise\n\nI’m an Android software engineer who knows about a bit about the web, not an expert web developer! Building BountyHour would have required excellent implementations of payments, tax, code control, timing systems, authentication, and a whole collection of non-technical skills that I just don’t have.\n\nDuring development, I could envisage a world where I eventually finished a functioning site, but… would I be able to actually run it? If there were issues with payments, could I sort them? Probably not! There’s also the fear of the site being used for money laundering, tax evasion, or countless other things that require an entire legal department to handle. Terrifying.\n\nAlso… security. I didn’t feel confident enough in my code to be sure that any payments logic would be immune to attack, that exploits wouldn’t exist all over the place, or even that private customer data (financial or personal) would be safe. The internet is a dangerous place, and it needs experienced people handling security, not tourists like myself.\n\nWhilst I could just about get the expertise for a previous startup (Creators.Direct), that was primarily an app that also had a web component. BountyHour would be entirely web, with any app coming far later and being non-essential.\n\nAs mentioned in scope, a better web engineer / company could get this done far quicker, so it actually makes far more sense to just contract someone else to do… all the work. At that point though, what’s my purpose, just the “ideas guy”!? Anyone can do that, without any technical experience.\n\nInterest\n\nUnfortunately my interest in handling a project of this scale dwindled once I saw… the scale. If I had infinite free time I could probably keep going, but the opportunity cost of other potential projects was way too high.\n\nI also essentially lost interest in most web development once I “got it”, with Android dev being far more enjoyable, understandable, and logical for me personally. If I was coming from a background of not knowing much about software, web development could definitely have held my interest. However, coming from an expertise in a totally unrelated area, spending 6-7+ years learning web to the same level I know Android was not an appealing concept!\n\nDespite thinking about the project a lot, I only actively committed to it on 14 days, across a 1 month span. That really isn’t much, despite it still living on in my head 9 months later.\n\nWhat did I learn?\n\nWell, the primary learning was the vast amounts of information around modern web development I gained!\n\nConsidering I went from zero knowledge, gaining hands-on experience creating new things with Next.js, Node.js, Prisma, TypeScript, Tailwind, tRPC, Next.js Authentication, and Shadcn UI is so, so valuable. It now means I have some sort of reference point when looking at web-related libraries / projects.\n\nBefore starting I didn’t really get the Node stack, and utilities like Theo’s T3 Stack really helped jumpstart the learning experience. This was also my first time relying heavily on GitHub Copilot to help me with new topics, and it was absurdly powerful!\n\nAdditionally, this was my first time using Linear for project management, and it was good to experience it from a broader perspective than I experience in my day job. The project was small enough that a text file probably would have sufficed, but trying out new tools is always good!\n\n\n\nFinall, this was my first time handling the project structure for a system with a site, API, components, developer tools, etc, and keeping track of the ~100 actively modified files required. I’m happy the repository seemed “tidy”, without all the clutter and dead code that a first project typically includes. Everything felt logical, I understood what it all did, and felt confident in changing anything.\n\nConclusion\n\nSoftware development is hard. Starting a new company is hard. Doing both in an area you don’t really have expertise is very very hard (and maybe foolish). Even with all the help possible (Copilot for learning, Shadcn UI for design), it’s too much for one person.\n\nRealistically I massively enjoyed the BountyHour building experience, and I’m extremely grateful I admitted defeat before spending multiple years building a doomed project. The now open-source code might help someone eventually, especially the form handling, most likely myself in a few years when I need to understand similar code!\n\nI hope something like BountyHour exists eventually, since I strongly believe highly skilled software engineers solving seemingly unsolveable problems is mutually beneficial for both the problem haver and the problem solver. I could absolutely see myself on both sides of that relationship, if you know of anything similar on the market let me know!\n\nHopefully this short post-mortem was helpful in some vague way, despite essentially being a way for me to say goodnight to BountyHour just before the domain’s expiry. Goodbye, BountyHour!\n"
    } ,
  
    {
      "tags"     : "Career, Software engineering",
      "title"    : "Ten years in tech: 7 career lessons from my decade in software development 🐸",
      "excerpt"  : "This August marks exactly 10 years since my first software development job! I’ve hopped between industries, companies, and seniority a lot in this time, hopefully learning a few useful lessons. Well, at least 7 anyway.\n",
      "url"      : "/7-lessons-from-a-decade-in-tech/",
      "date"     : "Aug 1, 2024",
      "content"  : "This August marks exactly 10 years since my first software development job! I’ve hopped between industries, companies, and seniority a lot in this time, hopefully learning a few useful lessons. Well, at least 7 anyway.\n\nIntroduction\n\nBefore diving into each job and the lessons learned, it’s worth pointing out how drastically the software development market (and of course my own situation) has changed in the past 10 years, especially the past 4. Gergely Orosz posts weekly about the state of the software engineering industry, but one takeaway is that some of the career moves I made would be impossible now.\n\nAdditionally, it’s very likely that reasons I left companies have been addressed by now, so any information in this article might be out of date, it is merely a snapshot of a moment in the past.\n\n7 lessons learned\n\nIf you’d like to skip aaaaallll the personal information, back-story, and explanations, here are the 7 lessons I’ve learned, 1 from each employer. They’re simply in the order I learned them, and as with all “lessons” they need to be evaluated critically not just blindly followed:\n\n\n  Take ownership of your own career.\n  Be honest with yourself about burnout.\n  Supportive colleagues are essential.\n  Pay attention to your job market.\n  Don’t be blinded by the money.\n  Try out different employer &amp; team types.\n  If a job seems too good to be true… you might as well interview!\n\n\n2014 - 2017: First Option Software\n\n\n\nWhat was the role?\n\nAs a Software Engineer at First Option Software I usually led work on the absurdly varied software systems used by a building surveyor for insurance claims, later focusing on building an Android app for a social media company.\n\nWhat was the best &amp; worst part?\n\nThe best part was the sheer variety of technology used, most of which had to be learned from scratch! It’s pretty rare even a full-stack fresh graduate gets to lead projects in Java, C#, PHP, SQL, and more on a daily basis, adding in VB6, ColdFusion, Android, iOS after a couple of years.\n\nThe worst part was the lack of guidance. As great as it was running massive, important projects by myself, and I learnt massive amounts daily, I did a lot of “cowboy coding” with nobody to show me better! With no code reviews, no seniors to learn from, and no personal objectives, it was nevertheless an excellent first job.\n\nWhy did I leave?\n\nMoney and specialisation. I self-taught myself Android outside of work, and building my games (e.g. Pixel Blacksmith) made me realise it was possible to actually enjoy software development, plus get paid more than a basic graduate wage for it.\n\nWhat career lesson did I learn?\n\nTake ownership of your own career. Your employer will take your preferences into consideration, but ultimately if you want to 2x, 3x, 4x your salary and/or work in a new area, you need to make that happen by yourself.\n\nThis means having an appealing LinkedIn, sharing your work publicly, not burning bridges when you leave companies, being friendly (but realistic) with recruiters, and staying up to date on your chosen technologies. It’s not automatic, but a good job is worth the effort!\n\nAll of my roles (after this first one) have been via recruiters reaching out via LinkedIn, so keeping that profile appealing to recruiters is absurdly important.\n\n2017 - 2018: Creators.Direct\n\n\n\nWhat was the role?\n\nI founded a content creator startup Creators.Direct with a friend, so I was Co-Founder / CTO. Realistically this involved everything technical, plus comms, legal, finance, management, and towards the end literally everything!\n\nWhat was the best &amp; worst part?\n\nThe best part was utilising my full-stack experience to build the backend, database, iOS app, Android app, client site, and having the complete control and vision over how the entire system operates and grows.\n\nThe worst part was… infinite essential work, and finite time to do it. With my (sales &amp; product) co-founder leaving early, I ended up spending half of my day fielding client emails, handling contracts, and contacting leads, and the other half building 3 large projects (Android / iOS / Web) and the backend to support them! Turns out 1 person can’t do the work of an entire team, regardless of hours worked.\n\nWhy did I leave?\n\nWorkload and dwindling resources. Since I’d work 16-20 hours, then sleep for 8, my body clock became completely detached from reality, and I’d shift a few hours later every day, waking up at arbitrary times of the day / night. This lifestyle plus barely making enough revenue to pay rent let alone save any wasn’t sustainable mentally, physically, or financially.\n\nWhat career lesson did I learn?\n\nBe honest with yourself about burnout. If you’re working ridiculous hours and aren’t enjoying the work, you can’t escape this by… working even harder. You need to delegate, offload responsibilities, take a break, or do whatever you need to protect your own mental health.\n\n2018 - 2019: ingenie (ANWB)\n\n\n\nWhat was the role?\n\nThis was my first dedicated Android role, as a Senior Android Developer at ingenie. This involved leading development on a driving tracking app for a large Dutch company (ANWB).\n\nWhat was the best &amp; worst part?\n\nThe best part was working entirely in Android, and having a very competent colleague! Whilst I had a reasonable amount of software development experience as a solo / cowboy developer, I was fortunate to work with a skilled Android Developer who taught me plenty of modern Android topics and libraries.\n\nThe worst part was being very distant from the client in terms of planning work and releases, and having no connection to the app’s mission as a non-driver. This was my first experience working in a slightly larger company (~30 people), and adjusting to work being translated through layers of management was a somewhat painful learning curve.\n\nWhy did I leave?\n\nManagement interference and better opportunities. As internal company politics became more and more prominent (new CEO, high profile firings, restructures, etc), all of my closest friends left the company. With no remaining ties, I started looking for better opportunities, and found them.\n\nWhat career lesson did I learn?\n\nSupportive colleagues are essential. Whilst I’d previously worked alone often enough, experiencing competent, funny, and intelligent colleagues to bounce ideas off was a game-changer. Once I’d had it, the loss was very painful, and would have been enough of a reason to leave in itself. This experience made me pay extra attention to the social aspects of work.\n\n2019 - 2020: Candyspace (ITV Hub)\n\n\n\nWhat was the role?\n\nI joined Candyspace, an agency with a long-standing major client (ITV Hub) that I would be 100% on. Initially my role was Senior Android Developer, progressing to Lead Android Developer.\n\nWhat was the best &amp; worst part?\n\nThe best part was my (and the 3-4 other Android developers’) work reaching millions of users, and leading development on an app that most people in the country have heard of. This made explaining my job to others very easy, and that name brand recognition will never stop helping me get new jobs! I’m extremely grateful for my manager taking a chance on my limited experience.\n\nThe worst part was the one-sided nature of the client / agency relationship. The power was entirely with the client (ITV), and the financial and workload limitations meant I hit the internal “ceiling” of earnings / responsibility quite early with no opportunity to progress further.\n\nWhy did I leave?\n\nEarning potential and becoming an internal employee. Due to changing personal circumstances, and the very strong Android developer job market at the time, I had a lot of favourable offers available (e.g. +40% base compensation). Additionally, I wanted to be “inside” a company, where I could actually influence what was done, how it was done, and the app direction.\n\nWhat career lesson did I learn?\n\nPay attention to your job market. If you’re noticing a lot of attention from recruiters on LinkedIn, and the numbers seem significantly higher than yours, maybe it’s worth talking to them. Conversations and interviews are free, and practice always helps, so it’s worth doing occasionally!\n\n2020 - 2021: Metro Bank\n\n\n\nWhat was the role?\n\nI was only here for 6 months (and was looking for a new job after 3), but I was a Lead Mobile Developer (Android) for Metro Bank.\n\nWhat was the best &amp; worst part?\n\nThe best part was… it’s hard to say. Perhaps the salary, it’s hard to find any other positives!\n\nThe worst part was, at least in the area I worked, the complete lack of conversation / webcams, friendliness, energy, competence, meaningful work, and everything else that is essential for a software development job. Perhaps a company adjusting to fully remote work is to blame for some of this, but it was truly unbelievable, and I’m hesitant to say too much publicly in case it comes back to bite me!\n\nWhy did I leave?\n\nCulture and work of any value, or the complete lack thereof. It is truly hard to overstate how much I disliked this role.\n\nWhat career lesson did I learn?\n\nDon’t be blinded by the money. I joined for good money, and I got good money, but it wasn’t even slightly worth the boredom and being able to feel my software skills and drive to learn / improve deteriorating in real time.\n\n2021 - 2023: Photobox\n\n\n\nWhat was the role?\n\nI joined Photobox as a Principal Android Engineer, later becoming a Principal Android Engineer / Interim Engineering Manager, and finally an Engineering Manager.\n\nWhat was the best &amp; worst part?\n\nThe best part was finally having the “inside” experience I wanted, and experiencing life inside a larger team (10+) and organisation (500+). Knowing that every part of the company (especially engineering) had skilled individuals was reassuring, and helped encourage improving skills.\n\nThe worst part was the higher-level company decisions resulting in high turnover. During my first few months there my iOS counterpart left, then my manager (who was a major reason I joined), then the company entered a protracted and technically extremely complex merger of equals, including the C-suite (goodbye CEO!). Whilst this resulted in lots of “gaps” letting me try out management, the relentless political manoeuvring at all levels due to the merger was painful.\n\nWhy did I leave?\n\nI don’t want to be a manager. Whilst I enjoyed interviewing, mentoring, and influencing product direction, I absolutely loathed the “politics”. This included information withholding, allocating budget, jostling for resources, and being forced to enforce and publicly support decisions I strongly disagreed with (e.g. going back on an employment agreement, losing us an excellent developer). I need to be genuine and open at work.\n\nWhat career lesson did I learn?\n\nTry out different employer &amp; team types. By now I’d been in a software shop with tens of projects, a bank, ran a startup, worked on a major app, in team sizes of 1-20 and company sizes of 1 - 1000. This varied experience helped me figure out what I actually wanted and needed in a role to actually stick around.\n\n2023 - Now: Seatfrog\n\n\n\nWhat is the role?\n\nI’m currently a Staff Android Engineer at Seatfrog, a traveltech startup!\n\nWhat is the best &amp; worst part?\n\nThe best part(s) are the get-it-done energy and freedom within a startup environment, and the work/life balance that comes with the absurdly excellent 4-day flexible &amp; fully remote week. This suits me absolutely perfectly, letting me work on other projects for at least 1 day a week (e.g. my MBA), and do whatever is needed to stay productive and keep improving.\n\nThe worst part is trickier to identify, but probably having 20 things I want to get done yet limited time in a day. Realistically this is a (positive) symptom of being empowered and invested in my employer’s product, so I can’t complain too much! There’s a constant balance between implementing new features, bug fixing, improving / removing lower quality code, improving testing, improving build process, etc etc etc. Prioritisation is hard!\n\nWhy did I leave?\n\nI haven’t, and hope I don’t anytime soon! With a startup, the biggest risk is lay-offs / financial problems, but this doesn’t seem to be a concern for the short-term. 🤞\n\nWhat career lesson did I learn?\n\nIf a job seems too good to be true… you might as well interview! For Seatfrog, I was offered work I wanted to do, for an interesting and unique product, with compensation &amp; flexibility that suited my fully remote lifestyle perfectly. Everything seemed literally a perfect fit, including all the interviewers I’d spoken to, so I assumed my chances were extremely low.\n\nDespite moving house a couple of weeks ago and having no internet (or desk!), I obviously interviewed well, and ended up with by far the best job I’ve ever had.\n\nConclusion\n\nThe tech job market changes often, and so do personal circumstances. Your job needs to meet your specific needs, so no article (including this one!) can accurately guide your career moves, or whether a specific job is right for you.\n\nHowever, reading a variety of anecdotal stories like this, and being aware of the career moves available, will help with the decision-making. Just because I shuffled between smaller companies instead of getting promoted within a large company doesn’t mean it’s right for you! Perhaps you’re better at internal politics yet worse at interviewing than me, so changing company is harder.\n\nI also made the risky decision to run my own tiny company, which completely drained my finances (and sanity / energy) but let me experience a very different working environment and have complete creative control. The intensity of this experience also let me “skip” a couple of years working my way up to senior, and it’s definitely something I couldn’t have done if I had an active social / personal life!\n\nWhilst doing my best to obscure any actual numbers (or any way to infer them), for transparency &amp; context this is an absurdly over-smoothed graph of compensation throughout my career so far, ignoring inflation. Obviously salary is only one aspect of a job, but it’s one that typically rises over time. Despite all the job changes, it’s been a fairly consistent progression (excluding the dip for running my startup!):\n\n\n\nAs for what’s next… I don’t know. I’m very satisfied in my current role, and since it’s within a growing company with empowered employees, I suspect any move I want to make (e.g. management, or more backend focused) can probably be handled internally saving everyone time, money, and hassle. There’s no “promotion” or “transfer” I want, my financial needs are met, it would be very hard to poach me.\n\nI’m looking forward to writing a follow-up post in 10 more years, and seeing how my perspectives and career plan have changed!\n"
    } ,
  
    {
      "tags"     : "Emulation, Text, Retro",
      "title"    : "Introducing a PLATO character overwriting emulator",
      "excerpt"  : "I recently had a GREAT idea to overlap pixel art letters to form artwork… then discovered it had been done in the 1970s by PLATO system users. Well, fine, I’ll build a basic emulator instead!\n",
      "url"      : "/plato-character-overwrite-emulator/",
      "date"     : "Jul 31, 2024",
      "content"  : "I recently had a GREAT idea to overlap pixel art letters to form artwork… then discovered it had been done in the 1970s by PLATO system users. Well, fine, I’ll build a basic emulator instead!\n\nEmulator\n\nAvailable at plato.jakelee.co.uk, the core concept is you type letters, and they get overlapped. For example o and l would draw a circle with a vertical line through it, and so on. Sounds simple, but it’s surprising how complex the images can get!\n\n\n\nMy emulator uses the original PLATO font “PlatoAscii.ttf”, available from the PLATO preservation group cyber1. Whilst I did install their full “Pterm” emulator and connect to their mainframe, it’s a little unintuitive for beginners!\n\nExamples\n\nExperimenting is most of the fun, but here’s a few examples courtesy of “Plato People” in 2002:\n\n\n\nFeatures\n\nThe emulator is very basic, and only supports full size characters (e.g. not superscript or subscript) included in the font file. This means some PLATO-specific symbols such as arrows are not available yet.\n\nWhilst a to-do list of features is available in the source code, possible future features include:\n\n\n  Ability to link to a prefilled creation (e.g. ?q=WOBTAX).\n  Support every character the real PLATO system can display.\n  Create a large library of example artwork.\n  Support multiple characters in a row for more complex artwork.\n  A way to view (3D?) how each character contributes to the final creation.\n\n\nTechnical details\n\nThe full source code is available in a GitHub repo.\n\nThe emulator is very simple, and not really an emulator! All it’s doing is layering each letter on top of each other, adding the ability to append / replace the text, and a bit of CSS styling on top. It’s hosted on GitHub Pages and runs entirely in the browser (obviously!).\n\nSince my JavaScript and CSS are pretty rusty, GitHub Copilot did a lot of the heavy lifting, especially around clicking to add / edit text. Thanks GitHub!\n\nLinks\n\n\n  To find out more about PLATO, and try the real thing, visit cyber1.org.\n  For more example emoticons, there are short articles from 2002 and 2012.\n\n"
    } ,
  
    {
      "tags"     : "Compose, Android, Graphics",
      "title"    : "How to make cutouts or transparent sections in Jetpack Compose",
      "excerpt"  : "At work recently we needed to have a semi-circular “cutout” from a rectangular box containing content. This was surprisingly tricky, so here’s an easy way to cut out arbitrary shapes from a Jetpack Compose Box!\n",
      "url"      : "/how-to-make-cutouts-in-jetpack-compose-boxes/",
      "date"     : "Jul 26, 2024",
      "content"  : "At work recently we needed to have a semi-circular “cutout” from a rectangular box containing content. This was surprisingly tricky, so here’s an easy way to cut out arbitrary shapes from a Jetpack Compose Box!\n\nAll code in this post is available as a GitHub repo.\n\nHow does a cutout work\n\nStripping away all the boilerplate code, the actually useful bit is:\n\nBox(modifier = Modifier\n    .graphicsLayer {\n        compositingStrategy = CompositingStrategy.Offscreen\n    }\n    .drawWithContent {\n        drawContent()\n        drawCircle(\n            color = Color(0xFFFFFFFF),\n            center = Offset(x = 0f, y = 0f),\n            radius = 100f,\n            blendMode = BlendMode.DstOut\n        )\n    }\n)\n\n\nThere are 3 key parts to this:\n\n\n  drawWithContent lets you customise how your Box (or other @Composable) content is drawn to screen, so that a circle (or any other shape) can be drawn on top of the content.\n    \n      The colour doesn’t matter, only the shape / position does.\n    \n  \n  As this new shape is being drawn on top, a blendMode of BlendMode.DstOut (a Porter/Duff blend mode1) states that the new shape should be subtracted from the original content2.\n  Setting the compositingStrategy to Offscreen forces the content &amp; any shapes to be drawn to a buffer then placed on screen at once3. This is required to allow the blendMode to function.\n    \n      Available since 1.4.0, previous versions can use alpha = 0.99f instead to force the behaviour.\n    \n  \n\n\nThat’s it! Draw the content, then draw a shape to cut away from the content.\n\nExamples\n\n\n\nNote: My background photo is a photo I took in Uetliberg, Zurich, Switzerland, in December 2023.\n\nWhilst the repo itself provides all of these examples in one large preview, standalone examples may be helpful.\n\nObviously the colours, shapes, background and contents are completely up to you, these are just simple samples!\n\n\n  \n    Code\n    Output\n  \n  \n    \n      @Composable\nfun TopLeftCircle() {\n    Box(modifier = Modifier\n        .size(100.dp)\n        .graphicsLayer {\n            compositingStrategy = CompositingStrategy.Offscreen\n        }\n        .drawWithContent {\n            drawContent()\n            drawCircle(\n                color = Color(0xFFFFFFFF),\n                center = Offset(x = 0f, y = 0f),\n                radius = 100f,\n                blendMode = BlendMode.DstOut\n            )\n        }\n        .background(color = Color(0xFFFFFFFF))\n    ) {\n        Text(\"There is text and other content here!\")\n    }\n}\n      \n    \n    \n      \n    \n  \n  \n    \n      @Composable\nfun MiddleLeftCircle() {\n    Box(modifier = Modifier\n        .size(100.dp)\n        .graphicsLayer {\n            compositingStrategy = CompositingStrategy.Offscreen\n        }\n        .drawWithContent {\n            drawContent()\n            drawCircle(\n                color = Color(0xFFFFFFFF),\n                center = Offset(x = 0f, y = size.height / 2),\n                radius = 50f,\n                blendMode = BlendMode.DstOut\n            )\n        }\n        .background(color = Color(0xFFFFFFFF))\n    ) {\n        Text(\"There is text and other content here!\")\n    }\n}\n      \n    \n    \n      \n    \n  \n\n  \n    \n      @Composable\nfun MultipleCircles() {\n    Box(modifier = Modifier\n        .size(100.dp)\n        .graphicsLayer {\n            compositingStrategy = CompositingStrategy.Offscreen\n        }\n        .drawWithContent {\n            drawContent()\n            drawCircle(\n                color = Color(0xFFFFFFFF),\n                center = Offset(x = 50f, y = 30f),\n                radius = 70f,\n                blendMode = BlendMode.DstOut\n            )\n            drawCircle(\n                color = Color(0xFFFFFFFF),\n                center = Offset(x = size.width, y = size.height),\n                radius = 70f,\n                blendMode = BlendMode.DstOut\n            )\n            drawCircle(\n                color = Color(0xFFFFFFFF),\n                center = Offset(x = size.width / 2, y = size.height / 2),\n                radius = 45f,\n                blendMode = BlendMode.DstOut\n            )\n        }\n        .background(color = Color(0xFFFFFFFF))\n    ) {\n        Text(\"There is text and other content here!\")\n    }\n}\n      \n    \n    \n      \n    \n  \n\n  \n    \n      @Composable\nfun ArbitraryShapes() {\n    Box(modifier = Modifier\n        .size(100.dp)\n        .graphicsLayer {\n            compositingStrategy = CompositingStrategy.Offscreen\n        }\n        .drawWithContent {\n            drawContent()\n            drawArc(\n                color = Color(0xFFFFFFFF),\n                startAngle = 0f,\n                sweepAngle = 300f,\n                useCenter = true,\n                topLeft = Offset(x = 30f, y = 30f),\n                size = size / 3f,\n                blendMode = BlendMode.DstOut\n            )\n            drawLine(\n                color = Color(0xFFFFFFFF),\n                start = Offset(x = 0f, y = 0f),\n                end = Offset(x = size.width, y = size.height),\n                strokeWidth = 30f,\n                blendMode = BlendMode.DstOut\n            )\n            drawPoints(\n                points = listOf(Offset(size.width, 0f), Offset(150f, 30f), Offset(170f, 100f)),\n                pointMode = androidx.compose.ui.graphics.PointMode.Points,\n                color = Color(0xFFFFFFFF),\n                strokeWidth = 30f,\n                cap = androidx.compose.ui.graphics.StrokeCap.Butt,\n                blendMode = BlendMode.DstOut\n            )\n        }\n        .background(color = Color(0xFFFFFFFF))\n    ) {\n        Text(\"There is text and other content here!\")\n    }\n}\n      \n    \n    \n      \n    \n  \n  \n\n\nReferences\n\n  \n    \n      https://ssp.impulsetrain.com/porterduff.html &#8617;\n    \n    \n      https://developer.android.com/reference/kotlin/androidx/compose/ui/graphics/BlendMode#DstOut() &#8617;\n    \n    \n      https://developer.android.com/reference/kotlin/androidx/compose/ui/graphics/CompositingStrategy#Offscreen() &#8617;\n    \n  \n\n"
    } ,
  
    {
      "tags"     : "Google Sheets, Google Play",
      "title"    : "How to bulk export your Android app's reviews into a Google Sheet for analysis",
      "excerpt"  : "Whilst Google Play Console’s “Reviews Analysis” feature is good, sometimes you really need the raw reviews to perform your own more detailed analysis on app feedback. This can be harder than it seems, here’s how!\n",
      "url"      : "/exporting-google-play-reviews-to-google-sheets/",
      "date"     : "May 26, 2024",
      "content"  : "Whilst Google Play Console’s “Reviews Analysis” feature is good, sometimes you really need the raw reviews to perform your own more detailed analysis on app feedback. This can be harder than it seems, here’s how!\n\nAccessing reviews\n\nIf you’re on the account that owns your app, there’s a handy “Go to Download reports” button under your app’s “Reviews” tab on Google Play Console:\n\n\n\nHowever, if you’re not, or need to provide access to someone else… it likely won’t work as you expect. Whilst there are app permissions for “View app information”, “Reply to reviews”, and even “Admin (all permissions)”, these will not grant access to the downloadable review data!\n\nInstead, you need to provide an account (not app) permission for “View app information and download bulk reports (read only)”:\n\n\n\nOkay, access is finally granted!\n\nDownloading reviews\n\nWhilst you can access the CSVs via Google Cloud Storage, they’re easy enough to access directly in Google Play Console. You’ll need to be on the main Google Play Console homepage (not your app’s homepage), and select “Download reports” in the side navigation.\n\nUnfortunately you’ll then need to click the download button on each month individually, but the end result will be a nice collection of CSV reports:\n\n\n\nImporting to a Google Sheet\n\nImporting a CSV into a Google Sheet is straightforward, but having to combine multiple files can lead to mistakes if you’re not careful!\n\nTo import multiple CSVs without overwriting existing data:\n\n\n  Create a new Google Sheet spreadsheet.\n  Click “File” -&gt; “Import”.\n  Upload your CSV file.\n  Set “Import location” to “Append to current sheet”.\n\n\nEach of the CSVs has a header row containing all the column names, so make sure to delete all of these! The easiest way is to just search for the text Package Name, the first column’s title.\n\nFinal notes\n\nYou should now have a Google Sheet containing all the information possible about your app’s reviews!\n\nAll the columns within the data are self-explanatory, with “App Version Code / Name”, “Star Rating”, and “Review Text” being the most useful. You might want to rearrange them to have key information (like the link) immediately visible:\n\n\nNext up: Performing basic text analysis on the reviews… 👀\n"
    } ,
  
    {
      "tags"     : "Postman, Certification, Review",
      "title"    : "Reviewing Postman's API Fundamentals Student Expert certification",
      "excerpt"  : "Postman has been around for a long time, and is widely used when working with APIs. In addition to documentation, it also has full training courses, including a student expert certification. Here’s a review!\n",
      "url"      : "/postman-api-fundamentals-review/",
      "date"     : "Apr 16, 2024",
      "content"  : "Postman has been around for a long time, and is widely used when working with APIs. In addition to documentation, it also has full training courses, including a student expert certification. Here’s a review!\n\nBefore diving into the course’s content, here’s my completion badge.\n\nGood\n\nStructured content\n\nThe course’s content is structured neatly into small, digestible chunks. For example, “Introduction to variables and scripting”, or “Generating code”.\n\nThere’s a clear top to bottom order to work through, and automatic completion tracking works well. Similarly, each page has subsections to break up the text, and there’s plenty of example gifs scattered throughout.\n\n\n\nLearn by doing\n\nAs you might expect from software that is available for free online, Postman encourages you to follow along as you go, and you’ll need to complete all the tasks to earn the badge. This hands-on approach ensures you’ll actually have real experience completing tasks, and is much better than simply skim reading test.\n\nSubmission tests\n\nMy favourite part of the course!\n\nTo check you have completed work completely, you:\n\n\n  Create a sharing URL with an embedded API key for your collection of API calls.\n  Fork a provided test suite collection.\n  Run your collection against this test suite: if the tests pass, so do you!\n\n\nThis approach showcases some of Postman’s advanced functionalities (sharing collections, testing APIs, collection variables) and proves they can have real world value. I was genuinely impressed by this, testing your product knowledge using the product itself is such a good idea.\n\n\n  \n    \n      Success response\n      Passing tests\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nSubmitting your work using Postman itself is done halfway through and at the end of the course, and is required for completion.\n\nShareable badge\n\nWhilst not a deal-breaker, having a badge on a neutral third party platform (“Badgr” in this case) is a nice reward for completing a course.\n\nThe rewarded badge is pretty simple, but accurately described what you’ve learnt from the course.\n\nIf you’re interested in more Postman badges, there’s over 30 offered!\n\nBad\n\nArbitrary scope\n\nWhilst the course does onboard you to a few Postman features, it seems somewhat arbitrary which are included and which are not.\n\nFor example, there is the “Generating code” section which shows you that cURL (and other) equivalents of a Postman request can be exported. This is a useful feature, but the course doesn’t mention the essential “Environments” feature whatsoever!\n\nThe decision on what to include doesn’t seem to prioritise either what is most useful to users (in this case students), nor what is core Postman functionality, and instead seems to emphasise the “cool” features.\n\nThis is understandable, since the goal is presumably to convince students Postman is a useful tool, but it does lead to the course being a bit disjointed, and a lack of clarity over why specific topics are being taught.\n\nSimilarly, if you are enthused by the course and want to learn more, there’s very little guidance around next steps besides claiming your badge. Postman has a whole engineer learning path, and even a suggested student project, but these aren’t treated as logical next steps. Instead, you’ll accidentally stumble across them and hope they’re suitable.\n\nUnclear target audience\n\nI’m not sure who specifically this course is targeted to. Whilst yes, “students”, presumably computer science students, are we talking about school children or university students?\n\nThe description states:\n\n\n  There are no pre-requisites to get started - you don’t even have to know what API stands for.\n\n\nHowever, a couple of the tasks briefly dive into JavaScript (to show off Postman scripting), assuming the audience already knows how programming in general works. The course also talks about getting and setting Postman-specific variables… and then mentions that JS comments exist!\n\nIf the course is also trying to onboard people to JavaScript, that’s a massive scope creep. Instead, it just touches on JavaScript for a few minutes then zooms forward to PATCH and DELETE requests. I can imagine this step losing anyone who doesn’t already have a working knowledge of JS.\n\nSimilarly, the course is often unclear if it’s trying to teach you generic web concepts (e.g. status codes, requests) or Postman. Either of these are pretty big topics, and teaching them at the same time risks muddying the waters around what is a globally accepted standard, and what is a Postman invention.\n\nInconsistent naming\n\nThis is a minor, petty complaint: Naming should be consistent throughout all documentation.\n\nWhilst names are typically accurate, and only suffer from inconsistent plurals or use of “a”, there’s a few examples where the “here’s what you should see” is significantly different from earlier in the page:\n\n\n\nWhilst yes, obviously it’s clear these are the same content… why are colours, names, capitalisations all just a bit different? It hints at a lack of technical writing review, throwing the genuinely useful information into doubt.\n\nThere’s also a few instances where the UI in an example picture is just slightly different to the current live UI. Nothing impossible to figure out, but just minor shuffling / changing of elements.\n\nSecurity error\n\nTo Postman’s credit, there is a warning that an error might be shown whilst sharing your collection for the test suite.\n\nHowever, it’s a scary error that a new user shouldn’t see! An email is also sent with [Action Required] in the subject line.\n\n\n\nEmbedded videos\n\nIt’s great that almost every step has a gif showing the action to avoid confusion.\n\nIt’s less great that these are full quality screen recordings at 2880x1800 resolution. Once there’s multiple 10MB+ gifs playing on the screen, scrolling can stutter.\n\nThese should be something like webp or avif, gif is a poor choice for the size and detail required.\n\nPoor sample data\n\nThere are 2 risky decisions made with Postman’s sample data.\n\n\n  All users read &amp; write from the same book database. Since the tutorial always uses the same example book, the databases consists of hundreds of variations of “To Kill a Mockingbird” with slight metadata changes! There’s a static API key for this data, so anything could be in there with no way to report.\n  When discussing query parameters, the course encourages querying Google in Postman as an example. This displays a cookie / authentication error, since it’s not an intended use of Google. This might confuse new students.\n\n\nConclusion\n\nThe course is OK. Not great, not, awful. Ultimately, it’s hard to know who I’d recommend the course to, since it’s too basic for experienced engineers learning Postman, too Postman-specific for beginner engineers, and too varied for any specific topic.\n\nWhilst the content is presented well, this doesn’t matter if it’s not necessarily the right content. If the course had started off with generic HTTP concepts, then moved on to Postman, there’d be more incentive to at least recommend the first few steps.\n\nI personally learned that Postman has unsurprisingly gained some new capabilities in the few years since I last used it, but none that I’m eager to actually start using myself. Admittedly I didn’t learn anything new about API basics, but I wasn’t expecting to from a student course considering I graduated from university 10 years ago!\n"
    } ,
  
    {
      "tags"     : "Google, Cybersecurity, Coursera",
      "title"    : "An unbiased detailed review of Google's Cybersecurity Professional Certificate 👨‍💻",
      "excerpt"  : "Did you know Google offers a Cybersecurity Professional Certificate? They do! I recently completed it, and wanted to share the good, the bad, and the confusing parts.\n",
      "url"      : "/google-cybersecurity-professional-certificate-review/",
      "date"     : "Apr 7, 2024",
      "content"  : "Did you know Google offers a Cybersecurity Professional Certificate? They do! I recently completed it, and wanted to share the good, the bad, and the confusing parts.\n\nBefore diving into the review, it’s worth mentioning that the learning platform used for this (Coursera) has a very rewarding referral program, but referral links are NOT used in this article. This way, the review is guaranteed to be impartial.\n\nWant to skip alllllll the words and detail? Skip to the conclusion!\n\nOverview\n\nA few useful links before going into detail:\n\n\n  Google’s Cybersecurity Professional Certificate\n  An example of the final certificate (mine!)\n  YouTube uploads of all video content, by Google\n  My notes made throughout the certificate process\n\n\nI won’t cover all the basic information around the objectives of each module, or the areas covered, since this is all available on the official site. Instead, I’ll cover all the things that aren’t discussed, far more interesting! However, it is worth referencing Google’s summary of the certificate objectives:\n\n\n  Understand the importance of cybersecurity practices and their impact for organizations.\n  Identify common risks, threats, and vulnerabilities, as well as techniques to mitigate them.\n  Protect networks, devices, people, and data from unauthorized access and cyberattacks using Security Information and Event Management (SIEM) tools.\n  Gain hands-on experience with Python, Linux, and SQL.\n\n\nDuration\n\nThe description of Google’s Cybersecurity Professional Certificate states “6 months at 7 hours a week”. This simply isn’t close to accurate, and is many times higher than the actual time required, regardless of experience levels.\n\nEach of the 8 courses consist of 4 “modules”, in theory a week of work. In reality each module will take around an hour of work, perhaps two for the very technical modules for complete newcomers. This gives a total time of around 32 hours (8 x 4), rounded down to 30 due to the last course containing far less detail. Nowhere near the ~180 estimated!\n\n32 hours is roughly a work week, and I can see from my notes that I completed the course in 16 days (20th March - 5th April). During this time I was also working on an unrelated university project (and have a job!), so my personal estimate with a lot of relevant existing knowledge is around 20 hours.\n\nIn conclusion, 20 - 40 hours to complete is more accurate, depending on experience.\n\nPricing\n\nThe certificate is served on Coursera, and whilst you can pay for access to the certificate itself ($49/month), it costs about as much as a month of “Coursera Plus” ($59/month) which provides access to the certificate and hundreds of others.\n\nAs such, Coursera Plus seems to make far more sense if you intend on completing any additional courses whatsoever, otherwise you’ll end up with overlapping $49/month subscriptions!\n\nYou also get a 7-day free trial with Coursera Plus, and can also apply for financial aid, although I’m not sure how that process works. There’s lots more info on pricing on Coursera’s site, or r/Coursera.\n\nMy background / aims\n\nAs hinted at earlier, I knew that this course would have quite a bit of overlap with my existing knowledge. I’ve worked as a software engineer for 10+ years, and have a personal interest in cybersecurity, encryption (my BSc Computer Science dissertation was on this!), and similar topics.\n\nHowever, as with a lot of my tangential knowledge, it’s been picked up at random through articles, conversations, and experiences at work or on side projects. This left me suspecting there might be some fundamental gaps in my knowledge, and this certificate confirmed that!\n\nI’d estimate around 30% of the course was new to me. Whilst the Python (Course 7), SQL (Course 4), and web portions were more of a refresher than anything new, the areas around incident detection and response (Course 6), and assets / threats / vulnerabilities (Course 5) were completely new information, with the other modules being a mixture.\n\nWith all that preamble finished, on with the actual review!\n\nThe Good\n\nVaried, high quality content\n\nPeople have different preferred learning styles, and I sometimes “bounce off” training courses because I don’t particularly enjoy videos, and far prefer reading or interactive activities. As such, I was very impressed with the variety of formats, and how it was all extremely consistently excellent.\n\nFor example, whilst core information is often provided in a video, it’s almost always expanded on in far more detail in text / graphic form in the next activity. This serves as a recap, clarifies any misunderstandings, and lets you absorb a bit more surrounding information.\n\nIn total, the formats offered, in approximate order of frequency, are:\n\nVideos\n\nTypically 2-8 minutes long, with a relevant Google employee on camera, there are so many of these that it adds up to around 14 hours in total! These videos often include animations, diagrams, or code when helpful, and are clearly filmed and edited professionally. More on these in Videos.\n\nNote that these are also all available on YouTube for free.\n\n\n\nReadings\n\nUsually 100-800 words, with relevant diagrams and links. The writing is very high quality, easy to understand, yet also accurate. In fact, despite usually finding plenty, I didn’t spot a single spelling mistake throughout the entire certificate! I wish these readings were provided as standalone content, as they’re some of the best summaries I’ve ever seen.\n\n\n\nQuizzes\n\nThese are short, 4-8 question multiple choice quizzes around recently covered content. They’re quite easy, usually require a 75% pass rate, and can be retaken if failed.\n\n\n\nFlashcards / Plugins\n\nThere’s a few formats of these, but they all revolve around clicking to view summaries of information learned. They all contain high quality artwork, and are useful recaps.\n\n\n\nPortfolio builders\n\nAfter learning about a new type of documentation (e.g. incident report), there’ll be a self-marked assignment to create an example of this documentation, with an example provided afterwards. I admittedly skimmed these activities usually, since they were quite a lot of paperwork that I’ve completed in the real world before.\n\n\n\nDiscussions\n\nThe only weak content type, “Discussions” give you a few prompts, and encourage you to answer in a few sentences, then reply to other student’s answers. These are typically open-ended questions such as “Why are you interested in learning about network security?”. Unfortunately these are almost entirely ignored (see “Discussions are pointless”), fortunately they are completely optional!\n\n\n\nLab activities\n\nSome technical content, such as learning Linux, Python, or SQL, had an interactive lab activity available via “Qwiklabs”. The Linux labs especially were very well-structured, more on those in Linux labs.\n\n\n\nVideo features\n\nWhilst playing back a video should be easy, it’s startling how awful some non-YouTube video players can be (and even YouTube’s sometimes). Luckily, this isn’t the case for Coursera, with the player containing education-specific features in addition to the basics. The full list of features offered, in order of usefulness is:\n\n\n  Playback speed is adjustable in 0.25x increments, from 0.75x - 2.00x. This is essential due to the slow talking speed.\n  Subtitles in English, with automatic alternatives for Spanish, French, Portuguese, and Chinese.\n  A full, accurate transcript below the video, with the sentence being spoken highlighted. Clicking a sentence skips to that part in the video.\n  The ability to make notes at timestamps in the video. Clicking “Save note” saves a clip, and the relevant transcript, and allows you to add your own comments. These can then be viewed in a central place for the course.\n  The video (or transcript / subtitles) can be downloaded in low or high quality for offline revision.\n  Some videos are interrupted by a multiple choice question halfway through, checking your understanding of the content so far.\n\n\n\n\nAmbitious scope\n\nThis certificate will teach you a lot, even if you’ve already had plenty of related experience.\n\nIt’s quite unusual for a single program to teach you languages like SQL and Python, how to use Linux, almost all the knowledge both technical and procedural involved in an entry level technical job, plus advice on preparing a resume and interviewing!\n\nThis scope means there’s a necessarily a quite fast pace, and I imagine most students will speed through some areas, then take extra days or weeks for additional independent study if this is their first time learning a technical topic.\n\nStill, this broad focus, delivered in a structured and high quality way, makes it an easy recommendation for anyone trying to get into cybersecurity.\n\nRecurring host\n\nEach course of 4 modules (so, 1/8th of the entire certificate) has a main host presenting the content. They introduce themselves, share some of their background, and present almost all of the content, with a few guest speakers scattered throughout.\n\nHaving a single person recurring in video after video on a topic helps you focus on the content itself and not the individual, and get used to their style of speaking. Additionally, each of these host speakers has a very relevant job at Google, such as the CISO of Google Fiber, a Technical Program Manager, or a mid-level Security Engineer.\n\nKnowing that the speakers work for Google in technical roles, not in video creation, gives the content extra authority, since the person speaking about it has real life experience. There’s a lovely video surprise at the end of the lab featuring these hosts, I won’t spoil it here!\n\nLinux labs\n\nDuring some modules, especially the Linux one, the course makes heavy use of “Qwiklabs”. This is an online virtual machine based learning platform with various cloud related courses available, and combines a terminal, instructions, and checking your work.\n\nWhilst this tasks start off very basic, and tell you exactly what to type, later on they’ll require actual understanding. The instructions will ask you to change permissions for a user, but you’ll need to remember the command’s functionality and syntax to actually complete it.\n\nImportantly, the labs strike a good balance between requiring you to type new commands to become familiar, whilst letting you copy and paste repeated or lengthy commands. This is accompanied by a very reliable progress checker, that offers hints if you’ve completed a task incorrectly. Sometimes a multiple choice question will be shown instead.\n\nFinally, Qwiklabs also has a gamified “League” system, where you get put into a group of other students and promoted / demoted through leaderboard rankings. This is more relevant for longer term learning, since I unsurprisingly shot to the top of my group after completing every Linux lab in the certificate!\n\n\n\nConnected modules\n\nAll of the modules within a course make sense together, and build on each other logically. Given the density of content I was concerned each video might end up being a standalone topic, but they’re all woven together well.\n\nFor example, each section will mention why the new content is related to the previous content, and an end of module (and course) wrap-up ties all the details together.\n\nRealistic external sites\n\nFinally, the references to external sources are up-to-date and realistic. Instead of referencing text books or mailing lists, sites like Reddit or Unix Stack Exchange are mentioned as far more realistic places to give &amp; receive help.\n\nThis also applies to the training on specific tools. Google’s products are mentioned when they are relevant and widespread, not focused on exclusively. For example, when talking about log analysis tools a tutorial on the industry standard “Splunk” was provided, in addition to Google’s “Chronicle” alternative.\n\nSurprisingly, this even applied when Google clearly has the superior option, such as free spreadsheet creation. Google Sheets is mentioned, but LibreOffice is also suggested as a possible alternative.\n\nConsidering this course is taught entirely by Google, I’m very impressed they resisted the urge to exclusively mention the products they presumably use (or work on) internally!\n\nPublic videos\n\nWhilst I personally found the videos OK, but only when enhanced with surrounding readings and activities, I know other people prefer them. Luckily, Google have provided all videos from the course on YouTube, for free!\n\nThis is a great gesture to give people a taste of the course, whilst also encouraging actually signing up to experience the course properly.\n\nPrestigious certificate\n\nDue to Google’s heavy branding, and the emphasis on “Cybersecurity Professional” instead of a specific topic, the final certificate actually looks and sounds quite impressive. I’ve interviewed plenty of software engineers, and to me it would look good on a CV / resume, although this of course might vary by industry.\n\nI’d definitely recommend adding the final certificate to LinkedIn, but I’d skip the 8 courses inside as they’re clearly just small single topic courses.\n\n\n\nThe course states that you’ll receive an email from Credly that lets you claim the certificate on Acclaim, a more independent badge platform I’ve used in the past. Assuming this comes through, I’ll likely add this to LinkedIn instead, as a more widely known and used platform than Coursera.\n\nThe Bad\n\nVery easy\n\nMost of this certificate can be skimmed through if you’re just interested in passing and not in actually learning. I was hoping there’d be some element of coursework or peer review, but it is entirely automatic marking of multiple choice quizzes or self-marking of documentation pieces.\n\nAs such, it requires discipline to actually do what is requested of you. I admit I skipped most of the lengthy documentation practices, since they were often essentially doing lab work again, but writing additional words around the actions.\n\nI’m not certain what the completion requirements are for a course, but I believe every video / activity needs to be marked as completed, and the quizzes correct above a certain percentage. This won’t be a problem if you’re actually paying attention to the material, and the occasional mistake (e.g. forgetting an acronym, misreading a question) is totally fine.\n\nWhilst being easy may sound positive, this has the downside of devaluing the certificate somewhat. If a “6 months” course can actually be skimmed through in a few days by cheating on quizzes, it’s far less valuable on a resume!\n\nFocus on individuals\n\nThis is perhaps just due to the focus of the course being complete newcomers to cybersecurity, but I was amazed how many individuals were sharing their personal career stories. These were all non-traditional (e.g. ex-military, originally in physical security, etc), and very obviously intended to highlight how “anyone can work in cybersecurity”.\n\nThe message itself is fine, but the constant emphasis was bizarre. Similarly, the importance of diversity and different backgrounds for new viewpoints etc was emphasised at least once per course, usually every other module. I don’t disagree, but I’m not sure if it needs to be constantly stated halfway through learning a new programming language!\n\nLength\n\nThe estimated time on every single activity is multiple times higher than reality. For example, a 10 question multiple choice quiz is estimated at 45 minutes, but ends up taking 6-7. Similarly, reading a few paragraphs about a new topic, even with note-taking, takes students an average of 10 minutes… but is estimated at 30 minutes!\n\nThis also applies to the courses as a whole, with every module completed prompting a pop-up telling you how absurdly far ahead of the unrealistic estimates you are.\n\n\n  \n    \n      Course estimate\n      Quiz estimate\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nCoursera navigation\n\nWhilst the navigation within each course is OK, I found actually trying to get around the Coursera site relentlessly difficult. I resorted to just bookmarking the next module to work out, since navigating from the Coursera homepage takes many, many clicks on confusing buttons.\n\nSimilarly, now I’ve completed my certificate, the site seems unsure how to tell me this. Sometimes it will say congratulations, sometimes it will ask me to verify my ID (not necessary for this course). In the screenshot below, the larger “Google Cybersecurity Professional” takes me to a random in-course module, whilst the smaller one takes me to the certificate frontpage!\n\nThis isn’t a deal-breaker, since the actual learning sections have different navigation, it’s just a confusing aspect.\n\nDiscussions are pointless\n\nMost modules have an optional discussion prompt, asking a few questions and encouraging you to reply to others. Unfortunately, this is optional, and there’s no benefit whatsoever to putting effort in.\n\nAs such, the discussions are pages upon pages of spam 1 letter / word posts &amp; replies, with the occasional actual answer. If the quality of these was higher, they could become useful resources for students, I’d recommend Coursera:\n\n\n  Allow the current replies to be seen before posting, to encourage discussion not just shouting into the void.\n  Add a minimum character count, even 50-100 would encourage useful answers.\n  Add a task early on in the certificate to set a name and profile picture. Currently, people are partially anonymous, and clearly don’t feel connected to their answers.\n\n\n\n\nLearning Python\n\nThis is a minor complaint, I’m not sure learning Python in a Jupyter notebook worked very well. Because it’s a mixture of Markdown and Python, the instructions and coding areas all overlap, making it relatively easy to accidentally delete the instructions!\n\nAdmittedly setting up a local environment would be too much work, but I’d have liked to see GitHub’s Codespaces used for an instant, realistic environment. Codespaces have a free usage quota, so this could have been a good opportunity to encourage users to make a GitHub account too.\n\n\n\nWireshark tutorial\n\nShort and sweet, the Windows Qwiklabs for Wireshark training took a couple of minutes to allocate the resources and open, then would disconnect as soon as I changed tab (e.g. to look at the instructions)!\n\nLuckily I already have some Wireshark knowledge, otherwise this part would have been unfinishable without installing it locally and hoping I’ve configured it as the guide expects.\n\nLimited career help\n\nWhilst the course pitches itself as including resume advice, interview training, and similar steps, in reality these are more like free resources or post-completion trials. You’ll finish the certificate with a resume, an elevator pitch, connections within cybersecurity communities, but this is all things you could do yourself reading any “how to get a job” guide.\n\nThe provided resume review is actually just a template, and the AI interview training is free anyway. I didn’t try it personally, as it’s AI driven with no human reviews. There is a free year’s membership to “Big Interview”, but this also seems to just record your videos and not have any human feedback given.\n\nAmerican graduates get access to “CareerCircle”, and all graduates get a 30% discount off the expensive CompTIA Security+, a pretty good deal (although other offers are often available).\n\nAll that being said, I’m not sure what more Google could actually do! Graduates have far more resources than non-graduates, perhaps an improvement would be a dedicated LinkedIn group of verified graduates to connect and share job opportunities.\n\nThe Confusing\n\nTalking speed\n\nThis is one of the most puzzling things I’ve ever seen in a video guide. The vast majority of people speak ridiculously slowly, far slower than a normal speaking speed, and with every word and gesture clearly carefully scripted.\n\nI usually listen to audiobooks and podcasts at 1.0x or 1.1x depending on the speaker, but I had every video in this certificate at 1.5x! What makes this even more bizarre is there were 2-3 clearly unscripted interviews that are at a normal speed, and due to the 1.5x video speed persisting they only serve to remind you how weird the other videos are.\n\nThe certificate’s videos are all available on YouTube, try listening to one and see how much more natural 1.25x or 1.5x sounds!\n\nTone of voice\n\nPerhaps simply a cultural difference, the very upbeat and enthusiastic tone of voice of the hosts never feels like a natural thing. The phrases are obviously intended to encourage you to continue, and be proud of yourself, but instead they just make me feel somewhat infantilised. A few examples of phrases that will crop up during videos:\n\n\n  “You did a fantastic job adding new knowledge to your security analyst toolkit … Keep up the great work!”\n  “Wow, well done!”\n  “I really enjoyed debugging this code with you”\n\n\nDistracting cast\n\nBeing careful about how I phrase this, the diversity within videos and activities is distracting.\n\nTo clarify, diversity and inclusion is obviously a positive, and many of the speakers give great justification for it. Similarly, those from non-typical computer science backgrounds may be reassured that career paths aren’t necessarily linear lines. However, this is the first time I’ve ever explicitly noticed the focus. The course hosts are exactly 50% male and 50% female, no problem with that. Instead, my confusion comes in the activities and interviews.\n\nIn a background image showing a typical workplace, when the 3 characters are a person with a hearing aid, a person in a wheelchair, and a person in a Hijab, this is an unusual combination in any culture or setting. It unfortunately distracts from the content itself, and overshoots the mark from “include representations besides stereotypical white men” into “include as many rarely represented groups as possible”.\n\nPerhaps the point where this is most noticeable is during a one-sided speech by… a deaf and aphasic (unable to speak) person using sign language, necessitating a voiceover by somebody else. Whilst it is theoretically possible that someone deaf has made it this far into the course, this doesn’t make sense for a video interview.\n\nOf course, if this person was sharing information they are an expert on, it’s obviously fine. However, they are only here to share their background story, making it (and others) feel like a token inclusion.\n\nUnneeded emails\n\nWe’re getting petty with the complaints, sorry! Considering the clearly linear path through the certificate, with each module and course linking to the next, do I need to be sent quite so many emails when I progress between the courses?\n\nI presume this is just due to technically finishing a standalone course and entering another, but it’s all a bit unnecessary.\n\n\n\nConclusion\n\nI really, really enjoyed Google’s Cybersecurity Certificate, both the contents and how it was presented. Despite the targeting towards newcomers, I’d actually recommend it to anyone who has worked in technology for a few years and wants to brush up on the basics, it’s a great way to ensure a basic understanding of the key topics involved.\n\nWhilst I’ve raised a few negatives above, after spending the equivalent of a full work week with the course it would be strange if I didn’t have improvement suggestions! It’s an excellent course, and I’m looking forward to trying out the similar Google UX Design Professional Certificate next.\n\nFinally, if you’ve got any questions about any aspect of the course before purchasing, feel free to leave a comment below (or contact me on any of the social links at the bottom). I know I had a few questions beforehand that I found hard to get simple answers to, especially around whether I should pay for the standalone certificate or Coursera Plus!\n\nHopefully this review has given you a better understanding of what to expect from Google’s Cybersecurity Certificate via my first-hand experience, and what a useful (if expensive) resource it is.\n\nAs a bonus, here’s how the final certificate looks:\n\n\n"
    } ,
  
    {
      "tags"     : "GitHub, JavaScript",
      "title"    : "Which social accounts are supported on GitHub profiles?",
      "excerpt"  : "A somewhat hidden feature of GitHub profiles is the special treatment of profile links from 12 social networks. Here’s a full list, how they are detected, and a way to check for yourself!\n",
      "url"      : "/github-profile-supported-social-links/",
      "date"     : "Mar 16, 2024",
      "content"  : "A somewhat hidden feature of GitHub profiles is the special treatment of profile links from 12 social networks. Here’s a full list, how they are detected, and a way to check for yourself!\n\nSupported social networks\n\nPutting profile links from any of the following websites as a link on GitHub should make the icon appear, and only your username shown. You’ve probably heard of most of them!\n\nThe supported networks are 10 traditional social networks:\n\n\n  Bluesky\n  Facebook\n  Instagram\n  LinkedIn\n  npm\n  Reddit\n  Threads\n  Twitch\n  X (formerly Twitter)\n  YouTube\n\n\nPlus, 2 decentralised networks:\n\n\n  Mastodon\n  Hometown (Mastodon fork)\n\n\nAdditionally, any verified emails or a verified ORCID iD can be displayed, although these don’t count as social accounts so won’t be covered in much detail here.\n\nHow are they detected?\n\nTraditional networks\n\nEach network has 1 or more regular expressions to detect profile URLs, and that’s it! Any URLs added to a profile are run through this, and a match triggers the special behaviour:\n\n\n  Bluesky\n    \n      ^https://bsky\\\\.app/profile/([^@/]+)/?$\n    \n  \n  Facebook\n    \n      ^https://(?:[^.]+\\\\.)?facebook\\\\.com/(?:[^/?]+/?|profile\\\\.php\\\\?id=\\\\d+)$\n    \n  \n  Instagram\n    \n      ^https://(www\\\\.)?instagram\\\\.com/[^/?]+/?$\n    \n  \n  LinkedIn\n    \n      ^https://(?:www\\\\.)?linkedin\\\\.com/(?:in|company)/[^/?]+/?$\n    \n  \n  Reddit\n    \n      ^https://(?:www\\\\.)?reddit\\\\.com/u(?:ser)?/([^/?]+)/?$\n    \n  \n  Threads\n    \n      ^https://(?:www\\\\.)?threads\\\\.(?:net|com)/(@[^/?]+)/?(?:\\\\?.*)?$\n    \n  \n  Twitch\n    \n      ^https://(?:www\\\\.)?twitch\\\\.tv/[^/?]+/?$\n    \n  \n  X\n    \n      ^https://(?:www\\\\.)?(?:twitter|x)\\\\.com/([^/?]+)/?$\n    \n  \n  YouTube\n    \n      ^https://(?:www\\\\.)?youtube\\\\.com/(user|c)/[^/?]+/?$\n      ^https://(?:www\\\\.)?youtube\\\\.com/channel/[a-zA-Z0-9_-]{24}/?$\n      ^https://(?:www\\\\.)?youtube\\\\.com/@[^/?]+/?$\n    \n  \n  Npm\n    \n      ^https://(?:www\\\\.)?npmjs\\\\.com/~([^/?]+)/?$\n    \n  \n\n\nI used a short JavaScript snippet to extract these, see “Checking for yourself” for more information.\n\nDecentralised networks\n\nIf your social link ends in @Something (specifically if it matches the regex ^https?://([^/]+)/@([^/?]+)/?$), a completely different system is invoked!\n\nTo try and determine if the URL is a decentralised network, a call is made to https://github.com/settings/nodeinfo_software?host=&lt;domain&gt;, which returns the decentralised network software being used. For example, https://mastodon.social/@Jake returns {\"software_name\":\"mastodon\"}.\n\nSince the regular expression and network name are stored in the HTML as try-nodeinfo-pattern and nodeinfo-software, it’s safe to assume the “NodeInfo” protocol is being used to determine if either of the two supported networks (Mastodon, Hometown) are in use.\n\nChecking for yourself\n\nAs mentioned, to fetch this information I wrote some JavaScript to look at the possible social link formats in a GitHub profile, and display their regular expression(s).\n\nThe output looks like this, with a * next to any decentralised networks:\n\n\n\nCopy and pasting the JavaScript below into the browser’s console on your GitHub profile will output a list of networks and associated regexes.\n\nAlways be careful what you paste into the console!\n\n// Script to extract supported social platforms &amp; regexes from GitHub profiles\n(() =&gt; {\n  const elements = document.querySelectorAll(\n    'span[data-targets=\"social-account-editor.iconOptions\"]',\n  );\n  const networks = {};\n\n  elements.forEach((element) =&gt; {\n    const titleElement = element.querySelector(\"svg title\");\n    if (!titleElement) return;\n\n    let title = titleElement.textContent;\n    const patternElements = element.querySelectorAll(\n      \"span[data-provider-pattern], span[data-try-nodeinfo-pattern]\",\n    );\n\n    patternElements.forEach((patternElement) =&gt; {\n      const patternValue =\n        patternElement.dataset.providerPattern ||\n        patternElement.dataset.tryNodeinfoPattern;\n\n      if (patternElement.dataset.tryNodeinfoPattern) {\n        title = \"*\" + title;\n      }\n\n      networks[title] = networks[title] || [];\n      if (!networks[title].includes(patternValue)) {\n        networks[title].push(patternValue);\n      }\n    });\n  });\n\n  return networks;\n})();\n\n\nConclusion\n\nThis simple but helpful feature is almost completely undocumented, with only a vague mention in GitHub’s docs and release notes as:\n\n\n  You can now add up to 4 links to any social accounts to your user profile, with special support for popular platforms.\n\n\nIt’s a shame GitHub don’t seem to be actively adding new platforms, especially with platforms like Kick, TikTok, Pinterest, Discord, etc all completely absent (although Bluesky &amp; Threads were added after this article was originally published). However, they are adding verified identities such as ORCID iD (added 2 days before this article!) to display on your profile:\n\n\n  \n    \n      ORCID settings\n      ORCID on profile\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nHopefully this article helps you improve your profile by including more aesthetic links!\n"
    } ,
  
    {
      "tags"     : "GitHub, Open source",
      "title"    : "How to add a new programming language to GitHub: an introduction to Linguist 🔡",
      "excerpt"  : "When viewing code on GitHub, have you noticed how syntax is almost always highlighted, and repositories have a breakdown of languages used? That’s due to Linguist! Here’s how to add a language.\n",
      "url"      : "/adding-github-language-with-linguist/",
      "date"     : "Mar 14, 2024",
      "content"  : "When viewing code on GitHub, have you noticed how syntax is almost always highlighted, and repositories have a breakdown of languages used? That’s due to Linguist! Here’s how to add a language.\n\nBefore we dive into how to add a language, we first need to cover what Linguist is, and what is needed before adding a new language.\n\nThroughout this post, I’ll be using the example language of “Lingo”, which I have raised a Linguist PR for. Feel free to refer to that PR if something seems unclear.\n\nWhat is Linguist?\n\nLinguist is an open source project run by &amp; used on GitHub itself (a “production dependency”), and watched over very attentively by at least one of the senior engineers there.\n\nIn its own words:\n\n\n  This library is used on GitHub.com to detect blob languages, ignore binary or vendored files, suppress generated files in diffs, and generate language breakdown graphs.\n\n\nThe most obvious usage of Linguist for me personally is this sidebar feature on every repository, helping indicate roughly what kind of code it contains:\n\n\n\nLess obviously, but far more significant for developer experience, is the ability of GitHub to identify and syntax highlight almost any file it is given. Whilst this seems simple for files like .js, what about if a file has no extension? Or, even worse, when multiple languages share an extension (e.g. seven languages have a claim to .m).\n\nLinguist solves all of this behind the scenes, with the help of contributors like you and me. Importantly, it (mostly) isn’t a team focused on writing new language parsers, instead it coordinates the use of existing software.\n\nLanguage popularity\n\nSo, you have a programming language that isn’t detected by Linguist. Congratulations, it must be a pretty rare language!\n\nLinguist only adds languages once they have a minimum level of usage, otherwise there would be thousands of languages that have only been used once for a hobby project. The guideline for adding a language (or a new file extension to a language) is 200 unique user/repo repositories.\n\nAs GitHub’s search often only shows results from the last few years, there is a little leeway here. For example, if there are &gt; 2000 results for a language across a wide distribution of repositories, it’s likely to be accepted even if 200 unique repositories aren’t found (source).\n\nNote: Adding a new file extension for an existing language has the same requirements as a brand-new language, to avoid a single language “claiming” too many extensions.\n\nLanguage requirements\n\nHere’s everything you need to submit a request for a new language to be added. I’d recommend gathering all this before actually implementing the new language, since it’s all required and can take time!\n\nLinguist’s contributing guide is the source for most of this information, but hopefully the step-by-step visual detail here will make it a bit more beginner-friendly.\n\nAs a reminder, I’ll be using my “Lingo” PR as a concrete example for all of these.\n\nColour\n\nThe easiest part! If the language is added, what hex code should it use in usage graphs? This is usually a colour based on the language’s logo, for example I used an orange #974413 as my language’s program’s logo is orange.\n\nSyntax highlighter\n\nFor your language’s syntax to be highlighted on GitHub, you need a syntax highlighter!\n\nThis is also known as a “grammar”. Luckily, it seems most text editors (e.g. TextMate, Sublime Text, Atom, VSCode) use the same format for syntax highlighting! This means if you already have a syntax highlighter installed to your preferred text editor, you can probably reuse it.\n\nAdditionally, make sure the repository has one of the accepted licenses, e.g. MIT.\n\nFor my language, I was using an MIT-licensed VSCode syntax highlighter that contained the necessary .tmLanguage.json file.\n\nReal-world samples\n\nTo help Linguist “learn” what your language looks like, as well as ensuring appropriate tests can be written, 2-3 samples of your language are needed. These should be real world code, that does something useful, and not short “hello world” style examples.\n\nAs before, these samples should be from a source with an accepted license.\n\nFor my language, I used 2 files I’d looked at recently when extracting .ls files from Adobe Director: AutoDismisser.ls and Progress.ls.\n\nProve usage\n\nThis can either be the easiest or the hardest step!\n\nIf your file extension is unique, search for your file extension with PATH:*.abc -IS:FORK. This (fictional) extension returns 130k results, which would of course be plenty.\n\nHowever, if your language shares an extension with an existing language, you need to use some sort of filter. This is typically done by including mandatory parts of your language’s files if possible, or more typically defining a regular expression to “catch” most of your language’s files. This is known as a “heuristic”, read on if you need one!\n\n(Optional) Heuristic\n\nAs mentioned, if your language’s extension conflicts with another, you’ll need a heuristic to let Linguist work out which language to use.\n\nYou’ll likely want a regular expression for this, and you can use GitHub’s search as a playground to refine it. If your language has unique characteristics, you can just use those, for example a language that uses mycommand: at the start of each line could use /^mycommand:/.\n\nMy language, Lingo, defines functions using on abc ... end. As such, I used a regular expression matching lines starting with on, then 1 or more words, followed (after x lines of function) with a line containing just end. This Regex looks like: /^on\\s\\w+([\\s\\S]*?)\\nend$/, here it is in context.\n\nAdding a new language\n\nOkay, so you have all your necessary parts! What now?\n\nLinguist’s CONTRIBUTING.md covers various ways to contribute to the library. I’ll be using GitHub Codespaces, since it’s the easiest to get up and running.\n\nGitHub Codespaces\n\n\n  Click the GitHub Codespaces link, and create a new Codespace (all accounts have a small free allowance).\n  Wait a few minutes whilst your Codespace spins up, it’ll look almost exactly like VS Code, but in a browser!\n\n\n\n\nAdding a language\n\nIn the terminal, enter script/add-grammar &lt;your repo&gt; (e.g. script/add-grammar https://github.com/markhughes/vscode-lingo-director).\n\nThis will add your syntax highlighter as a submodule, make a copy of the license, and update grammars.yml with a new source._ definition. Make a note of this new definition (e.g. source.lingo).\n\n\n\nOpen up languages.yml, find where your language should be alphabetically, and add a definition. This should be the same format as all the other languages, and include:\n\n\n  The language name.\n  The type (usually programming, sometimes data).\n  The color it should appear as on GitHub.\n  The extensions it uses.\n  The tm_scope, your syntax highlighter from earlier.\n  The ace_mode, you almost certainly want text, some languages have special modes.\n\n\nNote: For more detail on these values, see the top of languages.yml.\n\n\n\nAdding samples\n\nNow, some supporting information is needed. Create a folder with the same name as your language in /samples/, and put 2 real world samples inside.\n\n\n\nTerminal commands\n\nYour language now (probably) has everything it needs! However, we need to run a few scripts to tell Linguist about our new content:\n\n\n  Update the sample database by running bundle exec rake samples.\n  Update the syntax highlighter list using script/list-grammars.\n  Finally, run script/update-ids. This will give your language an ID inside languages.yml.\n\n\n\n\nYou can check your work is done by running bundle exec rake test. If that reports no errors, you can move on to raising a PR!\n\nIf you are adding a new language with a file extension conflict, you’ll likely have some failing tests. Time to fix them.\n\nLanguage tests\n\nAs mentioned, you only need to complete this step if you are adding an extension that is already in use. Luckily, it’s not much work at all.\n\nFirst, open heuristics.yml, and find or create your extension’s section (again, alphabetically). Add your language, and your pattern AKA heuristic.\n\nYou’ll also need to add a test for your heuristic, in test_heuristics.rb. This can just copy the format of existing tests, no special logic is needed.\n\nRun bundle exec rake test, they should all pass, and you are finally finished!\n\n\n\nRaising a PR\n\nFirst, make sure you’ve committed all your changes. In Codespaces, there is a source control tab (3rd), select it then click the + next to “Changes” to stage all your changes.\n\nAdd a meaningful commit message, click “Commit”, then “Publish Branch”. Choose your fork, and push the master branch up.\n\nOpening the Linguist repository will now give a prompt about your recently pushed branch:\n\n\n\nClick this, fill in the PR template carefully, and await feedback from the Linguist maintainers! I received feedback on my PR within a few hours, pointing out that I’d missed a test (oops).\n\nLinguist has strict quality requirements, so your PR will only be merged if it follows every step, and crucially adds a language with enough usage. It’ll also only be merged shortly before a release (every few months), be patient!\n\nConclusion\n\nGitHub is an extraordinary tool, consisting of hundreds of complex parts that do countless tasks under the hood to improve developer experience. Linguist’s ability to detect and highlight languages is one such feature, and having a basic understanding of how it works is useful!\n\nThere’s quite a few parts of Linguist that I’d like to look into more (e.g. how do the heuristics actually get used? What if two languages share the same name?), lots of which is hinted at in “How Linguist works”. It seems like a tool that has been happily growing for years, and is maintained with a lot of love.\n\nWhilst I’m doubtful my example language “Lingo” will ever actually be added (it was invented in 1989, and formally killed along with Director in 2017), going through the process was fun! I’m sure I’ll end up working with a slightly less obscure language in the future and need to go through this process.\n\nPull requests on Linguist are merged just before a release (if the language meets requirements), so the repository activity comes and goes. However, in 2024 so far there have been 10+ language / extension additions, and 20+ changes to syntax highlighters, language identifiers, or other internal data. I was somewhat surprised there are so many languages meeting the requirements (Slint, TextGrid, Edge, Glimmer, Roc)!\n\nHopefully this guide helped provide a more guided / visual version of the official contributing guide.\n"
    } ,
  
    {
      "tags"     : "Digital preservation, LEGO, Adobe Director",
      "title"    : "Open sourcing LEGO Junkbot, and tips for Macromedia/Adobe Director asset extracting 🕵️",
      "excerpt"  : "As part of a larger project, I recently extracted all code &amp; assets from a 20+ year old unplayable Adobe Director game: LEGO Junkbot. Here are the files, a discord, and some tips!\n",
      "url"      : "/lego-junkbot-files-and-director-tips/",
      "date"     : "Mar 8, 2024",
      "content"  : "As part of a larger project, I recently extracted all code &amp; assets from a 20+ year old unplayable Adobe Director game: LEGO Junkbot. Here are the files, a discord, and some tips!\n\nLEGO Junkbot source code\n\nThe GitHub repo contains all code, assets, and text files in unmodified format where possible. Adobe Director is pretty painful to use 20 years later, and searching for code and assets within VSCode or similar is much easier!\n\nThe project’s readme contains plenty more information, but a few highlights are:\n\n\n  All game sounds / music: /files/sound/\n  All level data: /files/levels/\n  All bricks: /files/legoparts/\n  Secret in-dev names of levels: /files/catalog/catalog text.txt\n    \n      Shoutout to Shit Stormsof Floaters by Eric (exciting!!! )!\n    \n  \n  Animation components: /files/dynamic/, filenames constructed by behaviour_legoparts manager.ls.\n\n\nNow, on with some tips for similar projects.\n\nTips\n\nPreparing project\n\nBefore you can extract your assets, you need a .dir file and a version of Director.\n\nI wrote a detailed guide to this, but the core steps are:\n\n\n  Download your .dcr file. You might need to hunt in the site’s source code.\n  Install the Director version closest to your project’s release date (Chrome will try to block the download). I chose “Director MX 2004 10.1.0” because it’s free.\n  Run the installer, using a legal free license.\n  Download ProjectorRays (again, Chrome will block the download).\n  Drag your .dcr file onto ProjectorRays, it’ll give you a .dir file 🎉\n\n\nNote: ProjectorRays can also be used via the command line.\n\nUnderstanding Director\n\nMacromedia/Adobe Director can be pretty confusing when opening a complex project, especially if you haven’t created Flash projects before.\n\nThere’s plenty of very detailed guides available elsewhere, but here’s the core things you’ll need to know:\n\nFilm metaphor\n\nDirector uses a film director metaphor throughout, so has some odd naming scattered throughout:\n\n\n  “cast” = a package or directory.\n  “cast member” = a file.\n  “score” = timeline of the movie / game.\n\n\nViewing assets\n\nIf you’re just trying to view assets, the “Cast” window will be your best friend. Pick a tab, switch to list view (horizontal lines button beneath cast tabs), and sort by type:\n\n\n\nWhen an asset is open, there will be appropriate controls for that time of content. This works pretty well, however you may prefer using an external editor.\n\n\n  \n    \n      Code\n      Text\n      Image\n    \n  \n  \n    \n      \n      \n      \n    \n  \n\n\nEditors\n\nExternal editors work by temporarily copying a file to your %TEMP% directory, then passing it to an external program.\n\nAn editor can be set in Edit -&gt; Preferences -&gt; Editors, editing a content type, then either finding your editor’s executable or scanning for a list of suggestions.\n\nI was pretty surprised how well this feature worked, allowing Director to work in harmony with software released 20 years later!\n\nExtracting files\n\nWhilst you can extract all the assets manually, by just opening them all in an external editor and resaving (like I did), there is a better way!\n\nn0samu’s DirectorCastRipper is an excellent tool that automatically extracts all common assets from a .dir and gives them appropriate names. Make sure you close Director before using it.\n\nThe supported types of data it can export, and output formats, are:\n\n\n  Bitmap, Picture: PNG, BMP\n  Sound: WAV\n  Flash, Vector shape: SWF\n  Shockwave 3D: W3D\n  Text: HTML, RTF, TXT\n  Field: TXT\n  Lingo code: LS\n\n\nI recommend checking Include member names in filenames so files have more useful names, otherwise just their numeric IDs will be used.\n\n\n  \n    \n      Options\n      In progress\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nFixing files\n\nSWA files\n\nSome Director sounds will be stored as .SWA, which most media players / browsers can’t handle. Luckily, this is just an .MP3 with metadata, so renaming the file makes it fully playable (source).\n\nBitmap bit depths\n\nSome of the bitmaps within a project might look very broken when they get exported. This happens when they have a “bit depth” of 1 (monochrome), a file format that isn’t widely supported.\n\nThis can be fixed by double-clicking the “1 bit” in the bottom left of the Director image editor, and selecting 8 bits instead.\n\n\n  \n    \n      Original\n      Exported\n      Fixed\n    \n  \n  \n    \n      \n      \n      \n    \n  \n\n\nBulk renaming\n\nThis isn’t specific to Director, but I wanted my source code files to be organised into their Casts (packages) as folders for easier navigation.\n\nWhilst DirectorCastRipper can export with names (see Extracting files), this also includes the cast name. For example, backgrounds_1_bkg1.bmp means:\n\n\n  Package / cast: backgrounds\n  ID: 1\n  Name: bkg1.bmp\n\n\nOnce the files were in their appropriate folder (e.g. backgrounds), I needed to strip the prefix from them. There are plenty of tools to do this, but I’ve always used Ant Renamer. Here’s the regular expression I used to remove all package_123_ prefixes:\n\n\n\nSecret hunting\n\nWhilst this could be a whole article (or series of articles!), there’s a few techniques for finding hidden info within an old project. Most importantly, get the data out first. Once you’re browsing your files in VS Code (or similar), searching will become infinitely easier.\n\n\n  Search for developer names. For example, I know a “Peter” worked on my project, so searching for his name finds lots of files / text involving him, like draft levels.\n  Search for expletives / emotion words. Words like “shit”, “hate”, “awful”, “sucks” might find hidden text buried away in game files. It’s how I found the internal level name “Shit Stormsof Floaters”!\n  Search for comments. Searching for your language’s comment syntax (e.g. -- or #comment for Lingo) might find clues like debugging log text.\n  Skim the assets. You’ll almost certainly find unused audio and image assets within the game files, and these can be easy to identify since you won’t recognise them from gameplay.\n  Look out of bounds. Sometimes assets are hidden outside the window boundaries during development, but will appear within Adobe Director’s stage.\n  Actually reading the code. The final step! Skimming over the code will help you find any disabled functionality (e.g. Junkbot has a hidden level editor).\n\n\nCommunity\n\nAs with any niche project, I learned a lot along the way. Perhaps most importantly, I learned that there’s a community of devs working on tools related to preserving Adobe Director projects. The developers of both ProjectorRays and DirectorCastRipper can be found in ProjectorRays’ cosy Discord server, and there’s plenty of Director-y discussion happening there.\n\nIf you find other Adobe Director resources from the last few years (e.g. a deep-dive into file formats) there’s a decent chance the author will be in that Discord server! For broader Shockwave discussions (with lots of FAQs), there’s also the larger Shockwave Discord server.\n"
    } ,
  
    {
      "tags"     : "Adobe, Decompiling",
      "title"    : "How to decompile an Adobe Director DCR file",
      "excerpt"  : "Heard of Adobe Flash? Well, it has an unloved older brother: Adobe Director! I recently needed to access the raw files behind a compiled Director DCR file, here’s how.\n",
      "url"      : "/decompiling-adobe-director-files/",
      "date"     : "Mar 4, 2024",
      "content"  : "Heard of Adobe Flash? Well, it has an unloved older brother: Adobe Director! I recently needed to access the raw files behind a compiled Director DCR file, here’s how.\n\nSince almost everything we’ll be using is deprecated and abandoned, I can’t guarantee the safety of any software mentioned here. I’ve used it all happily, but abandoned software can be a risk.\n\nThe plan is simple:\n\n\n  Install Adobe Director.\n  Decompile our DCR file.\n  Open it up.\n\n\nIf you’re interested in doing the same for Flash files (e.g. swf), I’ve previously written a guide!\n\nInstalling Director\n\nAdobe Director reached end of life in 2013(!), but luckily the installers are still available on Adobe’s site.\n\n\n  Scroll down to “Director MX 2004 10.1.0”. Newer versions are available, but this is fine.\n  Click “English Windows Installer” (or Macintosh if on MacOS). Your browser will almost certainly block the download, since it’s an .exe! As such, we’ll need to be insistent…\n  Right-click the link, select “Copy link address”.\n  Open a new tab, paste this link in.\n  Chrome will block it again! This time click “Keep”, and you’ll finally get your dmx2004_101_update_en.exe.\n\n\n\n\nOnce opened, this is a pretty typical Adobe installer. You’ll be asked where you want to install it, what you want to install (I chose default settings), and offered a free trial.\n\nYou can use the free trial if you want, but free licences for older versions are available on Adobe’s site.\n\n\n  \n    \n      Initial dialog\n      Installing\n      License\n    \n  \n  \n    \n      \n      \n      \n    \n  \n\n\nGreat, Adobe Director is now installed! Now for our file.\n\nDecompiling DCR file\n\nMy file in question was junkbot2_13g_asp.dcr, a web game from the early 2000s.\n\nI used ProjectorRays for this, a very simple to use decompiler that can decompile DCR, DXR, CCT, and CXT files.\n\n\n  Download the .exe of the latest release, 0.2.0 at the time of writing.\n  This download will also be blocked, and you’ll need to confirm you wish to download it.\n  Once it’s downloaded, drag your .dcr file onto the .exe and a .dir will be created in the same directory. Easy!\n\n\nHere’s how your working folder should now look:\n\n\n\nOpening DCR files\n\nYou can now just double-click any .dir file you have, and Adobe Director will open (after confirming you wish to continue your free trial).\n\nNote that I found opening Adobe Director for the first time required running the program as Administrator, presumably because it was automatically blocked by Windows.\n\nFinally, here’s our file open in Adobe Director:\n\n\n\nEnjoy!\n"
    } ,
  
    {
      "tags"     : "Next.js, t3.gg, Android, Learning",
      "title"    : "Opinionated guidance defeats decision paralysis: How Google and T3 help jumpstart a new developer's learning",
      "excerpt"  : "I recently dived into a world I knew nothing about, not even the language: Modern web development with Next.js. After completing the official tutorials, I was hit with decision paralysis when trying to start an actual project. The solution? Opinionated templates like T3.\n",
      "url"      : "/decision-paralysis-and-opinionated-guidance/",
      "date"     : "Feb 12, 2024",
      "content"  : "I recently dived into a world I knew nothing about, not even the language: Modern web development with Next.js. After completing the official tutorials, I was hit with decision paralysis when trying to start an actual project. The solution? Opinionated templates like T3.\n\nMy decision paralysis\n\nSo, I wanted to learn Next.js. This required learning the underlying framework (React), a new language (TypeScript), and even an entire ecosystem (npm). I also needed to learn about hosting, databases, APIs, and a million other things I vaguely understood but not enough to actually implement. Sounds easy!\n\nOf course Next.js has different versions. It also has completely different ways of architecting a project, each of which has an unconnected official tutorial (pages router or app router). It also has 4 ways of displaying content. Do I want SSG? SSR? CSR? ISR? WTF!\n\nAaaand that’s before we even get to the various SDKs and tools required, each of which has multiple alternatives. For an ORM do I want Drizzle, or Prisma? For authentication do I build it myself, use NextAuth.js, or a paid solution like Clerk? For the UI do I build it with CSS modules? Sass? Tailwind? A UI framework library?\n\nI have no idea what on earth I’m doing.\n\nInitial attempts\n\nI have 50 decisions to make, and no way of knowing which is an unchangeable commitment and which doesn’t matter. OK, so I need a starter project to make some of these decisions for me.\n\nSince my initial exploration into Next.js / React was via Vercel’s official tutorials, their templates gallery seemed a good place to start. I spent a few hours looking through the projects, and they always fell into one of four camps:\n\n\n  Skeleton (example): Templates that essentially gave me less than I ended up with at the end of the official tutorial. I’m a bit clueless on where to go first, and there’s too little here to really help.\n  Skeleton plus X (example): Almost all the third party templates follow this format. They provide a basic landing page plus whatever feature the company happens to offer. No better than a basic skeleton.\n  Cluttered (example): Templates that weren’t from a company often suffered from the creator adding random utilities they wanted. These probably help an experienced developer, but for a beginner just add pointless complexity and confusion.\n  The kitchen sink (example): Some templates tried to provide everything you could possibly need, and end up becoming word / code soup. The example provided has a “Features” list that is essentially gibberish for a new developer. Who needs “Automated ChatGPT Code Reviews” or whatever “CVA” might be, I just want a modern template to start with!\n\n\n\nVercel’s Next.js template gallery\n\nI committed some time to a couple of these templates (especially Precedent), and left feeling a little burnt out and lost. I felt adrift in a sea of a thousand options, with only random opinions from companies and articles to guide me.\n\nWhilst the scattered articles, GitHub repos, and tutorials are helpful for someone learning a specific feature or library, for someone trying to learn the entire thing from scratch a more complete solution is needed.\n\nEnter T3\n\nLuckily, I’d long followed someone called Theo AKA “T3” on Twitter / X. I followed for his general tweets about tech, and didn’t know he was influential in Next.js / React, nor that he was primarily a video creator. When I was looking on Reddit for template recommendations, someone recommended him, and I discovered he has a very popular template!\n\nAfter being burned on the various Vercel templates, I was sceptical initially. However, T3 seemed to have a clear goal: providing the core functionality, and drawing a strict line about what you need to choose. More importantly, all of these decisions were documented, instead of just “it’s here because I want it to be”.\n\nHaving these choices documented meant I could make an educated decision about whether I agreed with them. For example, “Bleed Responsibly” discusses his approach to bleeding edge tech, and how it needs to be considered. It shouldn’t be used for core functionality (e.g. database), but is fine to use if it’s easy to migrate away (e.g. tRPC). Similarly, the non-negotiable stance on TypeScript and type safety provided some reassurance that this isn’t a “wild west” template that will have unsafe or unnecessary code scattered around.\n\n\nT3’s template rationale\n\nAfter some light customisation during the installation process (essentially “do you want to use feature X?”, I chose yes for all), you have a mini-site! It has a database, can read and write data, and already feels like it can do something useful. From this, it’s easy to imagine the first steps in creating your own project on top.\n\nFinally, the documentation is absolutely excellent. Not only is the mindset and decision-making described in detail, there are sections that provide more information and help than I could ever ask for:\n\n\n  Folder structure: Describing the overall file structure in detail to avoid getting lost.\n  Library introductions: Absolutely crucial in helping me understand the project, libraries like Prisma are described in just enough detail. Code examples from the actual project are used, helping them make sense in context.\n  Recommendations: Once T3 has gained your trust, it uses this to help guide your next steps. Importantly, it provides multiple options for each problem, and encourages you to avoid using things unless you actually need to. A breath of fresh air coming from “kitchen sink” style projects!\n  Community: There’s a Discord server with 20k members, and the discussions are mirrored online for easier searching.\n\n\nAll of these combined meant I went from completely lost and considering learning something else, to having a project that made sense, that I felt confident in, and I was ready to start building on. Wahoo!\n\nComparisons to Android\n\nAll of this confusion without any real authoritative source felt somewhat familiar throughout. Finally, I realised… this is what it felt like to first learn Android 10 years ago!\n\nIn the earlier days of Android development, Google was far less opinionated than they are now. They didn’t provide guidance on databases (Room), asynchronicity / threading (Coroutines), architecture (MVVM), or much besides the absolute basics of putting images and text on the screen.\n\nWith Android, a lot of the developers were coming from a Java perspective (like myself), so inevitably brought over a lot of the conventions. For example, RxJava and similar libraries became obvious choices due to the amount of existing knowledge. Whilst most of these libraries became somewhat standardised, they were all from different sources, so there was no guarantee they would work well together. Similarly, they didn’t necessarily make sense in the context of Android.\n\nAfter a few years, Android developers ended up essentially using Java libraries, with various fixes and workarounds glued on top. This was fine, but often ended up with far too many options for simple functionality like using a SQLite database. Some developers like myself ended up building their apps (e.g. Pixel Blacksmith) on top of total dead-end ORMs that are now abandoned like Sugar ORM (don’t use this!).\n\nOnce an authority, or in this case the authority, steps in and makes recommendations, it’s a massive relief. Developers don’t need to learn 5 different ways to complete a simple task, they can just learn the Google-endorsed way and they’ll be at home in most codebases.\n\nGoogle is now very comfortable defining “modern Android development”, including the language, libraries, IDE, and various project settings. Excellent.\n\n\nGoogle’s definition of modern Android development\n\nDiscovering T3 and instantly wiping away the endless decision paralysis around Next.js felt like the same story, told in a few days not years and entirely within my own head.\n\nHow do Google / T3 help?\n\nBy providing an answer, with rationale, developers can actually get started on writing code. Whilst experienced developers can absolutely debate whether library X or Y is better, as a beginner you just want to be told which one to start with. You’ll likely end up learning both eventually, and making this decision is far easier when you understand the other moving parts.\n\nBoth Google and T3 are very opinionated. This is completely intentional, and provides a “happy path” for getting basic functionality working. Sure, you might need to swap out libraries if you have a niche need, but realistically the vast majority of apps (web or mobile) have identical base requirements. You need to fetch data, you need to store data, you need to display data, and you need to update data.\n\nI’m absolutely envious of developers who enter the Android ecosystem when it is already mature, as I did with Next.js. When a technology is new and exciting it’s essentially chaos, with countless alternatives for every part of your app, and no way to tell which will become dominant in five years. Joining late lets you skip learning multiple similar approaches, and just learn the one that the community has embraced.\n\nOnce a baseline of understanding has been achieved, it’s drastically easier to compare different options.\n\nConclusion\n\nT3 kept me interested in Next.js / React / Tailwind / Prisma. Google kept me from straying away from Android for long.\n\nAs you’ve probably realised from the contents of articles on here, I’m usually not particularly opinionated on choosing certain libraries over others. If it works, and is widely adopted, it’s probably good enough. I’d much rather learn a whole new ability than learn how to store data in yet another ORM library!\n\nHowever, publicly discussing &amp; debating these opinions is useful for the long term health of an ecosystem. It’s just not what a beginner necessarily needs to read.\n\nAll the time saved comparing libraries and approaches on my current project is extra time to carry on developing within the T3 stack, and ignore (for now) all the alternatives!\n"
    } ,
  
    {
      "tags"     : "GitHub Actions, CI, Android",
      "title"    : "How to increment a project's version code automatically after a GitHub release using GitHub Actions",
      "excerpt"  : "Releasing software can be awkward, especially when working in a complex ecosystem like Gradle for Android. Recently, I at least removed one pain point by autoincrementing version number after a build has been published: here’s how!\n",
      "url"      : "/incrementing-version-automatically-after-release/",
      "date"     : "Jan 15, 2024",
      "content"  : "Releasing software can be awkward, especially when working in a complex ecosystem like Gradle for Android. Recently, I at least removed one pain point by autoincrementing version number after a build has been published: here’s how!\n\nOverview\n\nTo autoincrement a version number inside a GitHub Action, we need the ability to do 4 tasks:\n\n  Automatically make changes to the repo: Using a Personal Access Token.\n  Find the version number, increment it, and commit it: Using gh-action-increment-value.\n  Trigger the workflow on a GitHub release: Using on: release:.\n  Put all the parts together.\n\n\nThe ability to do these tasks with example versioning is available as a GitHub repository (example log), read on for a step-by-step guide.\n\n1. Making changes\n\nTo autoincrement the version number, your workflow needs permission to modify your repository. If you’ve got some sort of branch protections on (you should!) such as requiring PR approvals or preventing force pushes to your main branch, you’ll need to bypass these. This can be done with a Personal Access Token (PAT).\n\nCreating a PAT\n\nPersonal Access Tokens can be created on the “Developer settings” section of your personal GitHub settings. There are 2 options for creating a PAT:\n\n  “Tokens (classic)” are easier to use but riskier, as they apply to all repositories.\n  “Fine-grained tokens” are in beta. They only last a year, but there is much more control over which repositories and permissions they can access.\n\n\nSince we need somewhat risky permissions (pushing commits), I’d recommend using the fine-grained tokens despite the extra effort. These unfortunately have a maximum expiry of 1 year, but can be scoped to just the repository that needs version incrementing. Whichever option you pick, make sure it has the ability to read and write the contents of your repository that needs autoincrementing.\n\nHere’s how mine looked:\n\n\n  \n    \n      Repository access\n      Permissions\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nOnce your PAT is generated, you’ll only have one chance to copy it. I’d recommend doing the next step in a new tab.\n\nAdding your PAT\n\nNow you have a token that allows a script to act on your behalf, you need to safely store it in the repository that requires autoincrementing.\n\nTo do this, add a Repository Secret to your repository (Settings &gt; Secrets and variables &gt; Actions). Add your new repository secret with a descriptive name (I went for PAT), and it’ll look like this:\n\n\n\n2. Incrementing the version\n\nIncrementing a version number sounds simple, but can be pretty awkward if starting from scratch! You need to access the file that stores the version, find the number, increment it, and then make sure that gets into the actual build system.\n\nLuckily, a GitHub Action exists that does all this hard work for us!\n\nThe only task left is configuring where the file is, and the strings before and after the numerical version. Here’s an example config, that transforms {\"buildNumber\":3} into {\"buildNumber\":4}\n\n      - name: Increment value\n        uses: yoichiro/gh-action-increment-value@main\n        with:\n          target_directory: 'foobar/baz'\n          target_file: 'build_number.json'\n          prefix: 'buildNumber\":'\n          suffix: '}'\n          commit_message: 'Increment the build number to '\n\n\n3. Triggering the workflow\n\nThis is the easiest bit, since GitHub Actions supports this functionality already with on: release:. I’d also recommend adding workflow_dispatch so the workflow can be triggered manually:\n\non:\n  release:\n    types: [published]\n  workflow_dispatch:\n\n\n4. Putting it all together\n\nFinally, we can put all the pieces together!\n\nAs a reminder, we need to trigger the workflow on a release, checkout the code, and increment the version. Here’s the entire workflow, an explanation of unclear bits follows:\n\nname: On release\n\non:\n  release:\n    types: [published]\n  workflow_dispatch:\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@v3\n        with:\n          token: ${{ secrets.PAT }}\n          ref: main\n\n      - name: Increment patch version\n        uses: yoichiro/gh-action-increment-value@v5\n        with:\n          target_directory: ''\n          target_file: 'versions.txt'\n          prefix: 'versionPatch:'\n          suffix: ']'\n          commit_message: '[skip ci] Increments the patch version to'\n\n\nExplanation / Tips\n\nI won’t walk through each line of code, but I will highlight a few areas that can lead to mistakes.\n\nVersion code format matters\n\nAs I wrote in an issue on the repo, you may need to modify how your version codes are stored. This did not work:\n\next.app_versions = [\n    versionMajor:4,\n    versionMinor:1,\n    versionPatch:0,\n]\n\n\nThis did:\next.app_versions = [versionMajor:4, versionMinor:1, versionPatch:0]\n\n\nCheckout with PAT\n\nThe workflow checks out using the PAT (with: token: ${{ secrets.PAT }}) so that all actions have the ability to make changes.\n\nNeed reference to branch\n\nThe workflow specifically checks out main, otherwise when triggered by a release it will end up with a detached HEAD and be unable to commit any changes.\n\nUse releases not tags\n\nI initially triggered the action whenever a version tag was pushed:\n\non:\n  push:\n    tags:\n      - 'v[0-9]+.[0-9]+.[0-9]+'\n\n\nHowever, this would have caused problems if an old tag was ever pushed (e.g. for a historical release). As such, it now triggers when a release is published:\n\non:\n  release:\n    types: [published]\n\n\nSkip CI when incrementing\n\nI don’t want my main branch to rebuild after the version increments, so I added [skip ci] to the incrementing’s commit message. This may vary in your use case.\n\nAdd to existing workflow\n\nWhilst this post has focused on the version incrementing as a standalone task, it makes more sense to incorporate the actions into your current release workflow.\n\nIn my scenario, the incrementing only runs after the build has been created and published to the Play Store. If that fails, the version is not incremented.\n\nUsing for Android builds\n\nIf you’ve read this far as an Android developer, you’re probably wondering how this would work for Android, since we have both version name and version code. One solution that worked for me is to define the build version (using Semantic Versioning) in a dependencies.gradle file:\n\next.app_versions = [versionMajor:4, versionMinor:1, versionPatch:1]\n\n\nThe app-level build.gradle then reads this using:\napply from: rootProject.file('dependencies.gradle')\n\n\nNow the version name can be created from this as:\nversionName \"${app_versions.versionMajor}.${app_versions.versionMinor}.${app_versions.versionPatch}\"\n\n\nAnd finally the version code can be created by multiplying the version components by powers of 10:\nversionCode app_versions.versionMajor * 1000000 + app_versions.versionMinor * 10000 + app_versions.versionPatch\n\n\nFor example, [versionMajor:4, versionMinor:1, versionPatch:1] would become 4.1.1, which would become 4 * 1000000 + 1 * 10000 + 1 giving a version code of 4010001.\n"
    } ,
  
    {
      "tags"     : "Security, Passwords, LastPass, 1Password",
      "title"    : "First impressions migrating from LastPass to 1Password",
      "excerpt"  : "Almost exactly a year ago, I migrated from Chrome’s password manager to LastPass. Whilst this was luckily after the breach, the constant “oops, bad news” headlines destroyed my trust in LastPass. My renewal was coming up, but I migrated to 1Password instead: here’s how it went.\n",
      "url"      : "/1password-migration/",
      "date"     : "Nov 5, 2023",
      "content"  : "Almost exactly a year ago, I migrated from Chrome’s password manager to LastPass. Whilst this was luckily after the breach, the constant “oops, bad news” headlines destroyed my trust in LastPass. My renewal was coming up, but I migrated to 1Password instead: here’s how it went.\n\nWhy leave LastPass?\n\nSo yes, I don’t trust LastPass any more. Whilst my vault data wasn’t stolen, given the startling amount of data that was stolen (vaults, notes, website URLs) and how it was taken (keylogging a DevOps engineer via a Plex exploit), it’s pretty scary.\n\nAdditionally, their communications weren’t good enough for a cybersecurity company. When compared to Cloudflare’s extremely detailed writeups of even minor issues, almost radio silence about an absolute massive hack isn’t enough.\n\nFinally, the general “jank” around their website and app isn’t confidence inspiring. I ignored it before since, y’know, frontend design and cybersecurity have different scopes. However, a year of the Android login not always working, the extension interfering with website UI fields, the website never knowing if I’m logged in or not, and I’ve had enough.\n\nThe final straw was when I went to export my vault as a backup before temporarily trying 1Password, it downloaded a CSV with a few of the passwords, and displayed the rest of them in the browser. If they can’t even handle an export, are my passwords actually secure?\n\n1Password first impressions\n\nWhilst I’ve used 1Password at work before, I’ve not actually customised it or used half of it’s features.\n\nOf course, the main selling point of 1Password was… it being recognised as one of the best password managers. Since I wanted a cloud solution that worked on both mobile and desktop, it was a very easy choice.\n\nWhilst I was initially put off by the very “Apple-y” UI, it presents information in a simple, reliable, and fast way, which is what actually matters!\n\n\n\nThe timeline of my transfer process is a testament to how eager I was to leave LastPass, and how much 1Password impressed me throughout onboarding. A total of 25 minutes passed between my initial 1Password signup, and my LastPass account being permanently deleted! Considering I usually take multiple days to dwell on a decision, their positive word of mouth marketing had me mostly convinced before I touched the product.\n\n\n\n1Password good bits\n\nLastPass category import\n\nConsidering how much effort I put into deduplicating and organising my 1000+ passwords into ~10 categories with ~400 passwords total, losing my folders was a big concern.\n\nLuckily, this data migrated across perfectly (well, except for an odd missing character tag)! 1Password converted the categories into tags, and even took the extra step of adding a “LastPass” “LastPass Import [date]” tags.\n\n\n\nWhilst I appreciated this great password transfer, I was a little startled how it was done. Instead of requesting some sort of integration, or transferring a CSV, 1Password directly asked for my email, password, and 2FA code!\n\nSince these 3 things are information you should never give to a third party… I was pretty hesitant. I double &amp; triple checked that everything was legitimate before proceeding, and reasoned that 1Password were about to have all my passwords anyway, so they can have my LastPass account too! It was still a very disconcerting experience though, and I’ve never experienced it elsewhere.\n\nIt also normalises giving other companies your password and even 2FA codes, which in my opinion should absolutely never be required. Very risky behaviour.\n\nFree trial with no credit card\n\nFree trials are pretty standard with services like a password manager, but I was impressed that I could have a fully featured 14-day trial (including import) without providing any payment information. The signup form does ask for this information, but makes the “Skip” button nice and obvious, not relying on dark patterns to hide it.\n\nThis let me get my account set up, be confident it would suit my needs, and then pay without feeling any risk of dissatisfaction. This was definitely a great user experience.\n\nExtremely user-friendly\n\nOverall, the onboarding was really, really smooth. Despite actually needing quite a lot of things from me (download a desktop app, install an extension, back up a PDF, verify email, understand the actual product), it was done so smoothly that I felt very little friction.\n\nI was perhaps a little jaded by my experience with LastPass’ site, and was actually somewhat surprised when pages actually loaded quickly, kept me logged in, and didn’t have UI elements in weird places.\n\nWatchtower is great\n\n1Password’s “Watchtower” is their version of LastPass’ “Security score”. It doesn’t suffer from the same odd negative points (LastPass removed points for allowing mobile access, and for caching my vault offline), and I love the clear HaveIBeenPwned integration.\n\n\nNote: The 1 weak password is a temporary unchangeable one.\n\nHowever, it isn’t perfect. The app shows a score with no definition of the maximum, and is influenced by factors I’m not sure are correct. For example, it flags that I don’t have 2FA setup on 71 of the websites (I do, 1Password just doesn’t know about it). My score is 1029, yet “Fantastic”, implying this score goes up to 1100? 1200? Who knows!\n\nAdditionally, I wanted to share a screenshot of my security score for this post, and couldn’t. Instead, I’d have to Tweet this rather marketing-y message:\n\n  My Watchtower security score in @1Password is 1029 (Fantastic) 🤩 🏖️ ✅\nhttps://watchtower.1password.com/score/1029/\n\n\nThis link doesn’t seem to go anywhere, and just redirects to the homepage. I’ll skip Tweeting an advert, thanks!\n\nApp is very modern\n\nI can’t share any screenshots of the app (boo, security policy), and weirdly enough the Play Store &amp; documentation images don’t seem to match what I can see in front of me.\n\nThe app (v8.10.18) implements an excellent dark mode, and looks more like a digital bank than just a password manager. It’s got plenty of options (e.g. changing how autofill functions), and clearly shows that they’re technically competent, a stark contrast to the LastPass app.\n\n1Password not-so-good bits\n\nLogged out during payment\n\nWhilst on the screen to enter my card details, I got distracted looking in a banking app to use a different card to usual. I can only assume this somehow took more than 10 minutes, since when I finally found my card and entered the details, upon clicking “Submit” I was told my session had expired, and I needed to login again (and re-enter my card details).\n\nI do understand the security benefits of this, but I really wish I’d been told my session had expired before I typed in all my details and clicked submit! Not a big deal, but a minor annoyance.\n\nAfter creating an account, I noticed that this timer can be sent to any value, a nice quality of life feature.\n\nDoesn’t understand Android logins\n\nThis may just be a quirk of transferring from LastPass with Android logins, but 1Password doesn’t seem to understand their format. These URIs are in the format android://abc123 yet 1Password saves them as http://android://abc123, and then complains that they aren’t https!\n\n\n\nDoesn’t understand local IP logins\n\nSimilarly, it treats local IPs like URLs. This technically makes sense, but if I’m logging onto a local server only accessible from my PC, it’s only on HTTP. It would have been good if local IPs could be excluded from this check.\n\n\n\nMultidomain logins\n\nLastPass had a feature where it understood that multiple subdomains of the same domain might use the same details. For example, login.example.com might use the same authentication as account.example.com, and they can be treated as the same site.\n\nUnfortunately it looks like this didn’t transfer across properly, since some passwords got duplicated (and flagged as such). For example, auth3.uber.com and auth.uber.com are clearly the same site, yet I’ve ended up with 2 records. This wasn’t a big problem, I just went through and deleted the less useful copy of the ~40 duplicates.\n\nA minor annoyance at this stage was when deleting a duplicate login, the now unduplicated login would remain in this list. A small bug, but one that made deleting duplicates a bit more awkward.\n\n\n\nCheckout is in USD\n\nFinally, 1Password uses dollars for all payments and doesn’t include tax until the end. This obviously simplifies things from their end, but for a British customer used to prices including VAT, it was an unpleasant 20% price hike at the end of the checkout process. However, this was countered by all prices being in dollars, so the real price being less than I subconsciously expected!\n\nThe price went $35.88/yr to $43.05 when I selected my country (20% VAT), but this is £34.79 so… almost the same number we started with.\n\nConclusion\n\n1Password is good, use it!\n\nI’m really hoping I don’t have to make another of these posts in a year, migrating to yet another password manager because 1Password has had some catastrophic issue. Really really really hoping.\n\nSo far it’s been an improvement across all fronts, and has stopped password storage being a niggling “uh oh, might be an issue eventually” thought in the back of my mind. I’m also interested in their developer tools, hopefully I’ll have some time to play with their GitHub Actions / VSCode / git integrations at some point.\n\nThere’s also a Fastmail integration that I might try. I currently use a unique email per service (all automatically routing to my real email via a catch-all), but another way to achieve this is always appreciated.\n\nIt’s a great feeling being interested in what my password manager is developing, instead of desperately hoping they don’t have a problem!\n"
    } ,
  
    {
      "tags"     : "VSCode, LaTeX, Windows",
      "title"    : "How to install LaTeX (with previews & autocomplete) for VSCode on Windows",
      "excerpt"  : "I recently decided to learn the basics of LaTeX, a way of preparing documents primarily used in STEM academia. I also decided to use VSCode, as I do for almost all other work. This was not as easy as I expected, so here’s a complete beginner’s guide to getting LaTeX working in Visual Studio Code on Windows!\n",
      "url"      : "/getting-latex-working-in-vscode-on-windows/",
      "date"     : "Oct 22, 2023",
      "content"  : "I recently decided to learn the basics of LaTeX, a way of preparing documents primarily used in STEM academia. I also decided to use VSCode, as I do for almost all other work. This was not as easy as I expected, so here’s a complete beginner’s guide to getting LaTeX working in Visual Studio Code on Windows!\n\nInstalling LaTeX\n\nFirst up, we need LaTeX support on our system. This is where it instantly can get a little confusing!\n\nThere are multiple “distributions” of LaTeX (e.g. TeX Live, MiKTeX), which themselves basically package up “TeX”. These distributions have installers, then schemes, packages, it’s all a bit overwhelming to a beginner.\n\nLuckily, having just blundered through these mysteries, I can keep it nice and simple.\n\nDownloading the TeX Live installer\n\nYou need TeX Live, as it contains all the core components we’re after.\n\nInstall it from tug.org by clicking install-tl-windows.exe.\n\nDouble-click the file once downloaded, and… Windows will likely flag it as from an unknown source. Choose “Proceed anyway”. As this StackExchange answer states the same URL, and other search results reference it too, we can trust the source.\n\nRunning the TeX Live installer\n\nThe first screen we see has the “Install” option already selected, so click “Next”.\n\n\n\nThe second screen is more of the same, click “Install”.\n\n\n\nThis will pop up a scary looking window whilst it extracts the installer, this should only take a few seconds.\n\n\n\nWhen this has finished, a picture of a running cheetah will inexplicably appear for a few seconds whilst it finds a package server to connect to. This should disappear in a few seconds, replaced by the main installer.\n\n\n\nConfiguring the installation\n\nOkay! We’re ready to actually install LaTeX, or at least configure the installation.\n\nBy default, the installation will be 8GB, and includes every possible use of LaTeX. You are welcome to use that if you want, however it will take up to an hour(!) to install.\n\nIf you are happy to wait (not recommended), skip the next 2 optional steps and go straight to preparing VSCode. Otherwise, carry on reading.\n\nReduce install size (optional #1)\n\nInstead, I’d recommend changing the install scheme. To do this, click “Advanced”, and you’ll see a screen full of options.\n\nClick “Change” next to “full scheme (everything)”, and this dialog will pop up:\n\n\n\nChange the scheme to “basic scheme”, then click “Install”. This scheme is more reasonable, around 430MB, and will take a couple of minutes to install on an SSD.\n\nHere’s how it’ll look when finished:\n\n\n\nLaTeX is now installed! However, it does not include a crucial package we need (latexmk).\n\nInstalling latexmk (optional #2)\n\nDespite just installing a couple of hundred packages, one we absolutely need was not included! To fix this, first open up “TLShell TeX Live Manager”, which has now been installed.\n\n\n\nThis will show all of your installed packages by default. Under “Status”, change the view to “Not installed”. This will take a few seconds, as it is fetching data from a remote server.\n\nWhen it has loaded, scroll all the way down (use the side scroller!) to latexmk and latexmk.windows. Click the circle next to their name so they become ticks, then click “Install marked” near the top right.\n\n\n\nThis won’t take more than a couple of seconds. Once it is done, close any dialogs and TeX Live Shell.\n\nWe now have a fully functional LaTeX install! Oh, right, VSCode…\n\nPreparing VSCode\n\nThis bit is much more straightforward, thankfully.\n\nSearch for “LaTeX Workshop” and “LTeX - LanguageTool” in VSCode’s extensions tab, and click to install both. Only the first is required, but the second will give very useful grammar and spellchecking capabilities.\n\nMake sure you install the LanguageTool extension by “LTeX+”, as the one by “Julian Valentin” is not maintained and has been forked.\n\n\n\nVSCode will probably ask you to “Reload”, if not then close and reopen it yourself.\n\nTesting your installation\n\nOkay, you’re good to go!\n\nTo test this, create a new .tex file in VSCode. Add some basic LaTeX code, such as:\n\n\\documentclass{article}\n\\begin{document}\nHello I am just a small document.\n\\end{document}\n\n\nWhen you save this document, you should notice 4 things:\n\n1: New LaTeX buttons\n\nThe top right of your file should have buttons to build your LaTeX project and preview it.\n\n\n\nClicking the preview icon will hopefully… preview your file!\n\n\n\nTechnically, this is spinning up a local server, monitoring the file, generating a PDF, and embedding it. Luckily this is all done behind the scenes. However, the details are visible in…\n\n2: LaTeX Workshop output\n\nAt the bottom of your screen, the “Output” tab may show how much work went into this simple preview. Changing and saving your .tex file will make a flurry of activity reappear.\n\nI’d recommend changing bottom tabs unless you like seeing lots of logs every time you save!\n\nIt’s worth pointing out that this is also where any issues will surface themselves. For example, I initially didn’t install latexmk, and the error messages made this pretty clear. If you do happen to see any errors about unable to find x, try repeating the latexmk installation with the mentioned package.\n\n3: Lots of new files\n\nYour single .tex file now has 6 new friends!\n\n\n\nIt’s probably a good idea to configure your .gitignore file to ignore most of these. You can either use LaTeX Workshop’s .gitignore, or I use this minimal one for very simple documents:\n\n*.aux\n*.fdb_latexmk\n*.fls\n*.log\n*.synctex.gz\n\n\nUsing either of these, you’ll only commit the raw .tex file and the .pdf output.\n\n4: A LaTeX tab\n\nYour sidebar will now have a new “LaTeX tab”. Opening it will reveal a collection of LaTeX-y shortcuts, and the ability to easily insert any of hundreds of Symbols / TikZ commands.\n\n\n\nAll done!\n\nThat’s it! You now have LaTeX support within VSCode on Windows, complete with autocomplete, spellcheck, etc.\n\nI’m going to be using this tutorial to learn, there might be better ones but this seemed very accessible.\n\nMisc thoughts\n\nThis was far more complicated than it needed to be. I admittedly made it harder on myself by not just accepting the 1 hour 8GB install, but even then there were so many small areas of friction!\n\nThe LaTeX Project does do a good job from the documentation side, providing a high level overview without unnecessary technical detail. However, as soon as you click “Get”, and are met by multiple ways of getting multiple distributions for multiple OS… it falls apart.\n\nThe very first section starts off extremely promising, drawing complete newcomers in with this wording:\n\n\n  If you’re new to TeX and LaTeX or just want an easy installation, get a full TeX distribution. The TeX Users Group (TUG) has a list of notable distributions that are entirely, or least primarily, free software.\n\n\nUnfortunately, the link takes me to tug.org, which is actually timing out for me currently. Once it came back up, the result is not very intuitive. Is one of these better? Is one of them awful? No idea. Whilst I know from elsewhere that the top option is 100% what I want, I could easily have picked an incorrect option!\n\n\n\nOf course this isn’t too unusual in open source software, especially anything to do with academia. The installer did not need to be that complicated. The default install did not need to install every obscure package. I did not need to install an unsigned .exe. Etc.\n\nI would love to see a much more user friendly “quick install”. The vast majority of users don’t care which package server they’re connected to, they just want the ability to edit .tex files as soon as possible. Install the basics by default, and provide an easy way to install additional bundles of packages. Encourage new users, don’t give them a trial by fire.\n\nThere is the argument that as an academic tool, all users are likely to have higher education but… is that relevant? If I have an MSc in Physics from the 80s, that’s no guarantee that I can configure installed packages.\n\nRegardless, now it’s all setup, I’m looking forward to doing more than writing “Hello world”. Maybe there’ll be a tutorial or two on here in the coming weeks!\n\nUseful links\n\n\n  LaTeX Project homepage\n  LaTeX Workshop GitHub &amp; VS Marketplace\n  LTeX Language Tool GitHub &amp; VS Marketplace\n  Beginner-friendly LaTeX Tutorial\n  TeX Live\n\n"
    } ,
  
    {
      "tags"     : "HTML, Web Development",
      "title"    : "5 niche but powerful HTML elements that can prevent you reinventing wheels with JS & CSS (e.g. expanding content)",
      "excerpt"  : "A recent update to this site added a collapsible table of contents. After looking at a few JS / CSS solutions, I discovered there’s a details built-in HTML element that does everything I wanted! Here’s how to use it, and a few other useful HTML elements I’d never heard of.\n",
      "url"      : "/niche-html-elements/",
      "date"     : "Oct 13, 2023",
      "content"  : "A recent update to this site added a collapsible table of contents. After looking at a few JS / CSS solutions, I discovered there’s a details built-in HTML element that does everything I wanted! Here’s how to use it, and a few other useful HTML elements I’d never heard of.\n\nI’ll include a live preview for each element (which will inherit the site’s styling), as well as screenshots &amp; a link to a default version.\n\n&lt;details&gt; &amp; &lt;summary&gt; expanding content\n\nThese 2 are why I’m writing this post! The details element creates a hidden section of text that can be toggled by clicking the summary. This is very commonly required functionality, and even the default usage looks acceptable:\n\n\n\nThe arrow to the side behaves as you’d expect, and since it’s a unique HTML element it can easily be styled. Here is how it looks with my site’s styling (almost identical), followed by the source HTML:\n\n\n\n  Details\n  Something small enough to escape casual notice.\n\n\n\n\n&lt;details&gt;\n  &lt;summary&gt;Details&lt;/summary&gt;\n  Something small enough to escape casual notice.\n&lt;/details&gt;\n\n\n\n\nTips:\n\n\n  The details tag can have open added to it, making the content appear expanded initially.\n  When toggled, content around the details element will rearrange.\n  Mozilla developer docs.\n\n\n&lt;datalist&gt; suggested input values\n\nEveryone knows about select and option for dropdown lists… but what if you only want to recommend specific answers, not insist on them? Introducing datalist.\n\nDatalist is essentially a way to provide input with a list of recommended or suggested values, whilst still letting the user enter anything they want.\n\n\n\nThis could be useful for a search field displaying the user’s last few searches, common search terms, or a thousand other uses. It works by defining the datalist separately from the input element itself, connecting them with a list parameter.\n\nHere’s how it looks with my site’s styling, and the source HTML:\n\n\n\nChoose a flavor:\n\n\n\n  \n  \n  \n  \n  \n\n\n\n\n&lt;label for=\"ice-cream-choice\"&gt;Choose a flavor:&lt;/label&gt;\n&lt;input list=\"ice-cream-flavors\" id=\"ice-cream-choice\" name=\"ice-cream-choice\" /&gt;\n\n&lt;datalist id=\"ice-cream-flavors\"&gt;\n  &lt;option value=\"Chocolate\"&gt;&lt;/option&gt;\n  &lt;option value=\"Coconut\"&gt;&lt;/option&gt;\n  &lt;option value=\"Mint\"&gt;&lt;/option&gt;\n  &lt;option value=\"Strawberry\"&gt;&lt;/option&gt;\n  &lt;option value=\"Vanilla\"&gt;&lt;/option&gt;\n&lt;/datalist&gt;\n\n\n\n\nTips:\n\n  The datalist / list attribute also works on non-text inputs, e.g. numbers, times, ranges, and even colours!\n  It can be tricky-to-impossible to style the “popover” options, so it’s not ideal for sites with strong branding.\n  The accessibility isn’t ideal, with some screen readers not interpreting it correctly.\n  Mozilla developer docs.\n\n\n&lt;del&gt; &amp; &lt;ins&gt; change tracking\n\nTracking changes to a document is typically done via commit history, change logs, or similar techniques. Usually the changes are highlighted via some custom colouring (e.g. green for inserts, red for deletions). This is fine, but sites could / should be using the del and ins elements and styling them!\n\nThese elements make a lot of logical sense, just surrounding the deleted or inserted text with the tag. By default, browsers display this as strikethrough and underline, however background colours or highlighting would likely be a more modern approach.\n\nHere’s an example simply applying an additional background-color to both elements in CSS and removing the ins underline:\n\n\n\n\n\nThe del element is not very good useful in some scenarios and should not be used please.\n\n\n\nThe del element is &lt;del&gt;not very good&lt;/del&gt; &lt;ins&gt;useful in some scenarios&lt;/ins&gt; and should &lt;del&gt;not&lt;/del&gt; be used &lt;ins&gt;please&lt;/ins&gt;.\n\n\n\n\nTips:\n\n  del &amp; ins can have a cite attribute, containing a link to an explanation, changelog, etc.\n  del &amp; ins can have a datetime with a date string and optional time of the change.\n  Unfortunately as these niche elements are rarely used, screenreaders typically don’t handle them well.\n  Mozilla developer docs\n\n\n&lt;wbr&gt; word break suggestions\n\nOkay, this is the first element that I understand why it isn’t more widely used. I only read and write English, which tends to have relatively short words. As such, I don’t think about word breaks, they rarely if ever happen.\n\nHowever, this isn’t the case for languages like German (or scientific papers), where word structure differs and can result in surprisingly long common words:\n\n  In German, there are no noun clusters, the way you can string nouns together in English as modifying words to describe the final noun. The German solution for this is just to string them all together into a word.\n\n\nAs such, the ability to suggest opportunities for a word break location could be helpful. The example below uses a narrow space to show 3 line break solutions:\n\n\n  No recommendations. Notice how the letters fill each line, potentially resulting in awkward breaks.\n  wbr used multiple times, with some being used to break at a logical place.\n  &amp;shy; used multiple times, behaving similarly to wbr but with - symbols.\n\n\n\n\n\n1:ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ\n\n2:ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ\n\n3:ABCDEF&shy;GHIJKLMN&shy;OPQRSTUVWXYZ&shy;ABCDEF&shy;GHIJKLMN&shy;OPQRSTUVWXYZ\n\n\n\n\n1:ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ\n\n2:ABCDEF&lt;wbr /&gt;GHIJKLMN&lt;wbr /&gt;OPQRSTUVWXYZ&lt;wbr /&gt;ABCDEFGHIJKLMN&lt;wbr /&gt;OPQRSTUVWXYZ\n\n3:ABCDEF&amp;shy;GHIJKLMN&amp;shy;OPQRSTUVWXYZ&amp;shy;ABCDEF&amp;shy;GHIJKLMN&amp;shy;OPQRSTUVWXYZ\n\n\n\n\nTips:\n\n  Although &amp;shy; looks better, it has the downside of including the - in the text itself, preventing easy copying of the text. As such, wbr is probably better for anything that won’t be printed out.\n  Mozilla developer docs.\n\n\n&lt;ruby&gt; annotations above text\n\nDespite the cryptic name, ruby refers to a unit of typographic measure, which somehow relates back to showing pronunciation of (typically) East Asian characters or words.\n\nHowever, it can also be used for other purposes, such as showcasing an encryption cypher:\n\nJARBQCLDXE\n\nIt’s a somewhat confusing element to use, with 2 sub elements:\n\n  rt: The pronunciation tip to show above the previous word.\n  rp: The parenthesis used as a fall-back for browsers that do not support ruby. These are used for an opening and closing bracket around the rt, and are quite unusual.\n\n\nI’m going to use English numbers and words to simplify the examples. Notice how much more complicated the rp element makes the source code!\n\n\n\n\n  The total is: 101One hundred and one\n  The total is: 1One0Zero1One\n  The total is: 101(One hundred and one)\n  The total is: 1(One)0(Zero)1(One)\n\n\n\n\n* The total is: &lt;ruby&gt;101&lt;rt&gt;One hundred and one&lt;/rt&gt;&lt;/ruby&gt;\n* The total is: &lt;ruby&gt;1&lt;rt&gt;One&lt;/rt&gt;0&lt;rt&gt;Zero&lt;/rt&gt;1&lt;rt&gt;One&lt;/rt&gt;&lt;/ruby&gt;\n* The total is: &lt;ruby&gt;101&lt;rp&gt;(&lt;/rp&gt;&lt;rt&gt;One hundred and one&lt;/rt&gt;&lt;rp&gt;)&lt;/rp&gt;&lt;/ruby&gt;\n* The total is: &lt;ruby&gt;1&lt;rp&gt;(&lt;/rp&gt;&lt;rt&gt;One&lt;/rt&gt;&lt;rp&gt;)&lt;/rp&gt;0&lt;rp&gt;(&lt;/rp&gt;&lt;rt&gt;Zero&lt;/rt&gt;&lt;rp&gt;)&lt;/rp&gt;1&lt;rp&gt;(&lt;/rp&gt;&lt;rt&gt;One&lt;/rt&gt;&lt;rp&gt;)&lt;/rp&gt;&lt;/ruby&gt;\n\n\n\n\nTips:\n\n  There seems to be no way to space out the top text if it is wider than the bottom text.\n  Notice that the rp elements essentially exist just to optionally show a fallback bracket.\n  If the rp cannot be omitted, the easiest way to add them once your text is written. The same string is used before and after every rt tag.\n  The unusual text layout can make it hard to select / copy, so use sparingly.\n  Mozilla developer docs.\n\n\nConclusion\n\nOverall, I was amazed how many elements I had no idea even existed, let alone used them. Like most people, I learnt the basics ~15 years ago and pretty much stuck to them.\n\nWhilst I’m vaguely aware that W3C maintains HTML, and it is constantly evolving via RFCs… I don’t keep up with them whatsoever. Occasionally a new feature will burst into the mainstream, but there are countless others that didn’t quite make it, were only introduced temporarily, or just don’t make sense on the modern web. I’m glad these are all documented on Mozilla’s developer docs, which seems fairly authoritative.\n\nThere’s plenty more elements that I didn’t cover over on the Mozilla docs, for example what on earth are aside, search, kbd, or portal elements!?\n\nI also didn’t look into the oddities hidden within “Obselete and deprecated elements”, since they should no longer be used. How about a tt, xmp, or even a dir?\n\nIf I end up having a bit too much spare time and/or go slightly mad, I might make this site strictly follow the recommended usage of HTML elements, technically making an extremely accessible site. I doubt it’ll actually make a difference to anyone using screenreaders or search engines (since most sites don’t do it), but it might be a fun project!\n\nPS: RIP &lt;marquee&gt; 🫡\n\nHeader is from codewithfaraz.com, a great resource that really needs a more detailed table of contents.\n"
    } ,
  
    {
      "tags"     : "YouTube, GitHub Actions, OSRS, RuneScape",
      "title"    : "Introducing \"OSRS Ironmen\", a list of 150+ OSRS Ironmen YouTube Series ⚒️",
      "excerpt"  : "RuneScape is a game that creates &amp; fosters obsessive people: I was one of them! Nowadays, many create “ironman” accounts, with obscure and restrictive limitations. To keep track, I created “OSRS Ironmen” collating over 150 of these accounts and their progress videos.\n",
      "url"      : "/osrs-ironmen-list-of-youtube-series/",
      "date"     : "Oct 9, 2023",
      "content"  : "RuneScape is a game that creates &amp; fosters obsessive people: I was one of them! Nowadays, many create “ironman” accounts, with obscure and restrictive limitations. To keep track, I created “OSRS Ironmen” collating over 150 of these accounts and their progress videos.\n\nSimilar to the RuneScape Archive Project, this is intended as a “I’ll start it, then the community maintains it” kind of project. To that end, I used a 2 year old list as a starting point. As with my Jerma and Yogscast projects, GitHub Actions and YouTube’s API provide the core functionality, however this time there are a few changes. As usual, the codebase is open source on GitHub.\n\nBefore I describe the changes, the OSRS ironmen project is at: https://ironmen.jakelee.co.uk\n\nOverview\n\nI have previously written an in-depth technical write-up about my similar projects. Essentially:\n\n  There is a list of categorised playlist IDs &amp; their names.\n  Once a day (or whenever the list changes), a script runs that reads this list.\n  The script asks YouTube’s API for metadata about each playlist ID, formats the data, and displays it.\n  This list also includes category headers, which are used to manage table headers too.\n  All of this data is merged with a template into README.md, served to the site via GitHub Pages.\n\n\n\n\nChanges\n\nPlaylists not channels\n\nAs this project is about series not channels (and a single channel can have multiple series), it needs to make a different API call.\n\nLuckily YouTube’s API is pretty simple, and I needed to use /youtube/v3/playlistItems instead of /youtube/v3/channels. Whilst there is a /playlists call, it essentially provides the same response with less information!\n\nI also needed to collect quite different information from the API. Instead of view counts or subscriber counts, I wanted the title, publish date, and thumbnail of the first and last videos in the playlist. YouTube’s API has excellent documentation, and even an online playground, so this was pretty easy to work out.\n\nAdditionally, I discovered jq can use [-1] to refer to the last item in an array, which is very cool. For example, .items[0].snippet.title provides the first video’s title, and .items[-1].snippet.title provides the last video’s title. Simple!\n\nSubcategories\n\nWhilst past projects have had a few categories, this project needed a total of 5 categories with 17 subcategories! This required a few minor changes around how headers were handled, to ensure tables were only created for subcategories.\n\n\n\nToggling image visibility\n\nOriginally, displaying thumbnails was a nice visual feature. However, as the list grew, they made the page far too long and hard to parse.\n\nTo solve this, I wanted a way to hide all images by default, then let the user press a button to make them appear again. I tried a few different approaches, but I had somewhat unusual requirements:\n\n  All images should be invisible initially, with no brief visibility.\n  Images shouldn’t require any special CSS / classes, since then I wouldn’t be able to use simple Markdown.\n  It should be as simple and concise as possible.\n\n\nLuckily, I found this solution that uses an ingenious approach:\n\n  A CSS rule hides all image elements inside any element with the class hide.\n  The body element of the entire page has the hide class by default.\n  Pressing the toggle button will remove or add the hide class from body.\n\n\nThis solution was very efficient, and meant minimal code: 3 lines of CSS, 3 lines of JS, and a tiny change to the layout HTML.\n\n\n  \n    \n      Images visible\n      Images hidden\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nFuture improvements\n\nWhilst I’m happy with the project so far, it definitely has a lot of improvements that could be made. Most aren’t impossible, but would require a fair bit of work to get working smoothly!\n\nLuckily, as the project is open source, there’s always a chance someone else with more JS / Shell experience might contribute. Here are the main categories of possible improvements:\n\nData presentation\n\n\n  Sort all: Whilst the categorisation is good, there’s no way to view the most recent video overall, or the longest playlists. Fixing this would require some sort of “alternate view”, perhaps built up at the same time and hidden, like thumbnails are.\n  Sort by # videos: Currently, the playlist’s nickname is shown before the number of videos. This makes it impossible to sort by number of videos, which might be a desired feature.\n  “Controls”: The controls section is pretty messy, and the actual options (sorting columns, toggling thumbnails) aren’t intuitive. Fixing this requires some thinking about user experience, a weak area of mine!\n\n\n\n\nData availability\n\n\n  View count: Currently, there is no information on the views of a playlist / video, making popularity hard to guess. Fixing this would require making an additional API call either to the video endpoint for the first video, or the channel itself. The playlist views themself do not seem available via the API whatsoever.\n  Video length: Currently, only video title, date, URL, and thumbnail are available. Fetching any additional information (such as length) would require an additional API call per video.\n\n\nOther\n\n\n  Easier playlist submission: Whilst I’m very happy that one PR has already been raised &amp; merged, so far most submissions have come via reddit (r/ironscape &amp; r/uniqueironmen) or email. This is fine, but not scalable. There should be some sort of publicly editable list of “pending” playlists.\n  Automatic table of contents: Currently, the list of subcategories is manually updated. It should be generated, just as the table of contents in this article is.\n  Private video handling: Currently, private videos don’t break, but they don’t show a title or thumbnail so look weird. Fixing this would require looking back through previous playlist videos to find a public one.\n  50 video maximum: Currently, only the first 50 videos of a playlist are loaded (and a warning shown), since that’s the most YouTube’s API returns in one call. Fixing this would require implementing pagination:\n\n\n\n\nConclusion\n\nOverall this has been a fun little project, and I’m optimistic others will find it useful!\n\nI learnt a couple of new JavaScript tricks (e.g. toggling image visibility), and am so, so pleased with how positive the feedback on Reddit was. Eventually I’ll post it on the bigger r/2007scape subreddit, maybe after a bit more polish.\n\nThe next steps are:\n\n  Figure out a way to stop being a bottleneck for new playlist discovery. Becoming a pinned / word-of-mouth recommended post in ironmen communities would help.\n  Implement the higher priority improvements. To me, these are:\n    \n      Alternate “uncategorised” view to allow sorting all.\n      Pagination, removing the 50 video limit.\n      Adding subscriber or view counts, to get an idea of popularity.\n    \n  \n  Get other technical people to make improvements, to let the project evolve without me.\n\n\nIt’s been perhaps 10 years since I’ve logged onto RuneScape, surely my interest in it will fade soon, right?!\n"
    } ,
  
    {
      "tags"     : "Google Search Console, Web",
      "title"    : "Using Google Search Console to effortlessly monitor small hobby projects (or big ones!)",
      "excerpt"  : "Like a lot of developers, I’ve somehow ended up with a collection of mini-projects online that require no maintenance, are missing a few features, but still get some Google traffic. I used to use Google Analytics for this, but I’ve been really, really impressed by Google Search Console!\n",
      "url"      : "/using-google-search-console-for-hobby-projects/",
      "date"     : "Sep 21, 2023",
      "content"  : "Like a lot of developers, I’ve somehow ended up with a collection of mini-projects online that require no maintenance, are missing a few features, but still get some Google traffic. I used to use Google Analytics for this, but I’ve been really, really impressed by Google Search Console!\n\nWhat is Google Search Console?\n\nGoogle Search Console is a simple (and free) service to track how a site is doing from Google’s perspective. This obviously includes how highly ranked the site appears in results, but it also includes a lot more!\n\nFor example, are there any errors found following links? Are any pages giving conflicting metadata around canonical URLs? Are any pages loading too slowly?\n\nAll of these factors factor into Google’s search algorithm, as they are symptoms of a high quality site. As such, following recommendations to improve your site’s Google listing… also improves the quality in general!\n\nGoogle themselves describe it as:\n\n  Google Search Console is a free service offered by Google that helps you monitor, maintain, and troubleshoot your site’s presence in Google Search results. You don’t have to sign up for Search Console to be included in Google Search results, but Search Console helps you understand and improve how Google sees your site.\n\n\nWhy use it?\n\nThere are a lot of reasons to try out Google Search Console, even before getting into the actual features!\n\nSimple\n\nI don’t get on with Google Analytics. I get lost, I find it impossible to manage multiple sites, and get lost in trying to filter… dimensions… audiences… funnels. Google Search Console has drastically less data, but surfaces it in an extremely usable and helpful way.\n\nUsability can be somewhat subjective, but given the drastically smaller userbase of this platform, I get the feeling that Google’s designers have been more “free” to make changes. Below is the main overview, it instantly surfaces the 3 things I likely care about most:\n\n  How many users are visiting my site?\n  How many of my pages is Google listing?\n  How high quality are my pages?\n\n\nI’ll dive into each page in the features section, here’s how it looks:\n\n\n\nAutomatic subdomain verification\n\nIf you have verified a domain property (by adding a DNS record), adding a new subdomain requires no additional work. Just adding the subdomain sets it up, ready for tracking, since Google knows you own the entire domain.\n\n\n\nThis means the overall site stats are visible, whilst individual project sites can be dived into easily. I have ended up adding every domain I’m actively working on to Google Search Console, it’s very satisfying seeing random old projects experience traffic surges (due to proactive emails).\n\n\n\nNo code needed\n\nYep, no JavaScript needed. Your site’s code is completely untouched, there’s no security risks, there’s no increase in page load time, none of the downsides of other tracking solutions.\n\nSince Google owns Google Search (obviously…) and the Google indexing bot, Google Search Console is merely surfacing some of the data they have already collected.\n\nAs such, the only technical work needed is adding the DNS record to prove domain ownership, so that Google is comfortable sharing the data with you (see how to set it up).\n\nProactive emails &amp; achievements\n\nI am very confident that Google Analytics etc has the ability to set up emails for spikes in traffic. With Google Search Console however, it’s all already there.\n\nFor example, I recently added my settlers manual to Google Search Console, then a few days ago received an email letting me know it had received 80 users from Google Search! Obviously these aren’t big numbers, but as it’s a small project I haven’t touched in years, I would never have thought to check the analytics without this achievement notification.\n\n\n\nClicking the link in this email also lets you view historical achievements, useful for an instant look at how consistent the site’s growth it.\n\n\n\nMonthly summaries\n\nIf your project is your main source of income, or you spend a lot of time on it, then you’ll probably be checking the analytics daily. However, for a small project you did in a weekend a few years ago? It’s unnecessary.\n\nThis is where Google Search Console’s monthly emails are such a helpful feature. They provide a very high level view of how your site is doing, and I always give them a quick skim-read when they arrive.\n\nI won’t show all the detail (the screenshot would be very long!), but the monthly emails include:\n\n  The number of clicks, views, and pages with first impressions this month.\n  The top growing &amp; performing pages this month (and how many clicks they received).\n  The top growing &amp; performing queries used to find your site.\n  What type of device, country, and type of Google search the user found your site via.\n\n\nThis is extremely helpful data, all without any code being added to your site! I find the information on growing &amp; performing pages to be an especially interesting snapshot into why people are visiting your site.\n\n\n\nFinally, the “insights” feature lets you know which search queries you are in the top 5 results for, growing content, clicks per month, etc. For my site, it shows that despite all my high effort technical posts… people just want to read about gaming!\n\n\n\nQuality monitoring\n\nGoogle looks at your site regularly, to ensure their search results are up-to-date. If the site is added to Google Search Console, whenever it experiences something weird that dissuades it from showing your page in results, you’ll receive an email.\n\nThis could be anything from a page not being found, a redirect, conflicting meta tags, or duplicate content. Most of these “issues” aren’t actually errors, but they are potential problems that are worth looking into. For example, on my sites I have hundreds of unindexed pages due to:\n\n  Search results pages (correctly) stating the main search page should be indexed instead.\n  http:// pages that (correctly) state https:// is the main source of the content.\n  Old URLs that broke when I moved away from Wordpress’ /year/month/day/title URL format to my current /title.\n\n\n\n\nThese alerts have been pretty useful when I’ve accidentally broken something on one of my sites without realising, such as incorrectly stating my site should be HTTP!\n\nNo limitations / upselling\n\nNice and simple, the service is completely free and unlimited. Thousands of pages? Hundreds of domains? All free!\n\nSince Google wants you to improve your site to provide better search results, the free service they’re providing is mutually beneficial.\n\nWhat features does it have?\n\nOkay, so I’ve run through why I use Google Search Console. But what features are actually included in the site? Here’s all the options in the sidebar:\n\nOverview\n\n\n\nAs already mentioned, the main overview screen shows performance, indexed pages, and overall experience. “Enhancements” are also supported, but I don’t use them so can’t comment.\n\nThere’s also a “URL inspection” feature that shows you how Google Search views a specific page, and when it last updated. I use this feature to submit my new articles manually, since re-indexing can be requested.\n\n\n\nPerformance\n\nThis section is the most similar to more traditional analytics tools, as it provides detailed information on search queries, pages, countries, devices, etc.\n\nThe “pages” tab is especially interesting, since it shows the most popular pages across your site. Clicking each page lets you look at the search queries used to find it. Neat!\n\n\n\nThere’s also a page providing similar information on visitors from Google’s “Discover” feature but… these numbers have always been extremely low for me.\n\nIndexing\n\nThe indexing section provides information on why pages are or aren’t indexed (see quality monitoring).\n\nIt also has a few useful but niche utilities:\n\n  Video pages, to help your site show up in Google Video results.\n  Sitemaps, to help the Google indexing robot find content. I especially like that multiple sitemaps can be added, useful for subdomains!\n  Removals, where you can request Google hides some of your content (usually for privacy reasons).\n\n\nExperience\n\nGoogle Search Console also provides basic data on how quickly your pages are loading, how visible they are on mobile devices, whether they can use HTTPS, and similar concerns. This is a surprisingly helpful tool, and has helped me discover that various layouts have been broken on smaller devices.\n\nWhilst this data is split into “Page experience”, “Core web vitals”, “Mobile usability”, and “HTTPS”, the first page provides a perfectly sufficient view of all sections:\n\n\n\nSecurity &amp; Manual Actions\n\nI don’t know what these are! I have never had any issues detected, which can only be a good thing.\n\nMisc\n\nFinally, we have “Links”, which provides a great overview of internal &amp; external links. For example, most of my visitors come from Reddit, or Google, followed by GitHub. Since my main sites all link to each other via the top bar, this data is unfortunately somewhat inaccurate!\n\nAdditionally, due to Reddit’s pagination URLs any successful post on there will look like it has been linked to from thousands of different URLs.\n\n\n\nUnder “Settings” there’s also fairly standard options to invite other users or services, update your URL, export all your data, etc.\n\nHow to set it up?\n\n\n  Go to Google Search Console.\n  Click “Add property”.\n  Add the DNS record to your site (I did it via a Cloudflare integration).\n  You’re done!\n\n\nThere’s also a short but sweet series of guides from Google that provide an overview of everything Google Search Console can do.\n\nDownsides of Google Search Console\n\nOkay, so yes, despite being a massive fan of Google Search Console for the last year or so, it’s not perfect.\n\nMysterious data sources\n\nI don’t quite understand how Google Search Console can show which sites link to mine, but it can! I assumed the tool would only be able to show me Google search related data, but apparently not.\n\nDue to this mysterious data acquisition, I only really pay attention to the parts that focus on Google Search or my pages themselves. Perhaps it is linked to my Google Analytics?\n\nBasic data\n\nWhilst I really appreciate the data that is being surfaced, it’s always going to be limited. From search data alone you can’t gain the user journey / funnel information that most analytics systems provide.\n\nPersonally I think this is a very fair trade-off for being entirely free, irreplaceable (since nobody else has Google’s data), and requiring no code changes at all.\n\nNot realtime\n\nRecently I had a massive spike in views for one of my articles (the Need for Speed Unbound tips). However, I only found out about it when I reached a new 28-day record a week or so later. Whilst this didn’t have any direct impact, it did leave me feeling like I was stuck viewing aggregated past data, which is a bit less exciting than something more realtime.\n\nConclusion\n\nIn conclusion, I’ve no idea why Google Search Console isn’t more widely used!\n\nWhilst it isn’t perfect, it’s such a simple and easy to use tool that there seems to be no reason not to use it in combination with more comprehensive tools. Given the zero maintenance it requires and zero impact it has on my site’s users, I’ll definitely be staying subscribed to the emails.\n\nSince Google doesn’t directly make any revenue from it, I do understand why it isn’t promoted very heavily at all. However, I’m pretty confident any users of it will gain a bit of goodwill towards Google &amp; Google Search, so surely that makes it worth the effort?\n\n"
    } ,
  
    {
      "tags"     : "GitHub Pages, Jekyll, Web",
      "title"    : "Removing (or customising) the \"This site is open source. Improve this page.\" footer on GitHub Pages",
      "excerpt"  : "I use GitHub Pages to display Markdown files a lot. I use it for notes, game tracking, YouTube tracking, and plenty of other projects. Seemingly at random, some of these projects have an open source footer at the bottom. What is it, what controls it, and how can it be removed?\n",
      "url"      : "/removing-github-pages-improve-this-page/",
      "date"     : "Sep 13, 2023",
      "content"  : "I use GitHub Pages to display Markdown files a lot. I use it for notes, game tracking, YouTube tracking, and plenty of other projects. Seemingly at random, some of these projects have an open source footer at the bottom. What is it, what controls it, and how can it be removed?\n\nSince there’s multiple people asking the same questions as me, explaining it in a short article seemed sensible!\n\nWhat is it\n\nObviously, it’s a way to encourage visitors to improve your open source projects!\n\nClicking the “Improve this page” link opens up the current page directly on GitHub, letting any changes be suggested. For example, on forza.jakelee.co.uk the link goes to https://github.com/JakeSteam/ForzaUpdate/edit/master/README.md.\n\nThis URL cleverly includes the repository (JakeSteam/ForzaUpdate), the current branch (/master/), and the current file (README.md)!\n\nWhat controls it\n\nOkay, so the link can be helpful, but… what makes it appear?\n\nJekyll &amp; Primer\n\nWhen simple Markdown files are served via GitHub Pages, the “Primer” Jekyll theme (official example site) is automatically used. This is what causes the Markdown to be converted into HTML, although both remain accessible.\n\nFor example, my Markdown file tech.md gets rendered as tech.html by Jekyll using Primer.\n\nThe footer’s logic\n\nOK, so our Markdown file is displayed using Primer. That doesn’t explain where the footer comes from!\n\nAs Primer is open source, we can look at the source code for default.html, used to display the files. At lines 20-24, it all becomes clear:\n\n      {% if site.github.private != true and site.github.license %}\n      &lt;div class=\"footer border-top border-gray-light mt-5 pt-3 text-right text-gray\"&gt;\n        This site is open source. {% github_edit_link \"Improve this page\" %}.\n      &lt;/div&gt;\n      {% endif %}\n\n\nThe footer shows if:\n\n  The GitHub repo is not private (site.github.private != true).\n  The GitHub repo has a license set (site.github.license).\n\n\nHow can it be removed\n\nThe easiest solution, if your site does not actually need a license, is to just delete the LICENSE file you may have accidentally created when starting the repository. This is what I did for my Notes repository.\n\nHowever, if you do need to keep your license, we can easily remove the footer by overriding the Jekyll layout. To do that we:\n\n\n  Create /_layouts/default.html inside the repository. This can be done via the “Add file” dialog on GitHub.com by just typing the folder name too.\n  Copy across the contents of Primer’s default.html.\n  Remove (or customise) the footer (lines 20-24).\n  Save your new file, GitHub pages will redeploy your site, and the footer will be gone!\n\n\nConclusion\n\nI initially thought the “This site is open source. Improve this page.” footer was essentially an advert, letting any visitors know the site was being hosted via GitHub, and encouraging them to sign up.\n\nHowever, looking into the logic behind it and finding it only applies to repositories with a license set makes me suspect it’s primarily trying to help open source projects find contributors. Excellent!\n\nI was also very surprised that even basic Markdown file hosting uses the Jekyll build system. I use Jekyll daily (e.g. for this site!) and never considered that it was responsible for all my simple sites too. This is definitely a nice surprise, since it means I already know how to customise it extensively if I ever need to, since all the same techniques work.\n\nHopefully that helps anyone wanting to customise the basic GitHub Pages Markdown hosting, at the very least it taught me a few new things!\n"
    } ,
  
    {
      "tags"     : "Forza Horizon 5, Gaming, JavaScript",
      "title"    : "Introducing \"Forza Update\", a minisite automatically tracking the next Forza Horizon 5 season & series",
      "excerpt"  : "As you might have realised from my many previous Forza Horizon 5 posts, I play it a lot! Each week we get a new content drop, and I often got confused about update times due to timezones. To solve this, I created a new minisite.\n",
      "url"      : "/forza-update-timer-miniproject/",
      "date"     : "Sep 10, 2023",
      "content"  : "As you might have realised from my many previous Forza Horizon 5 posts, I play it a lot! Each week we get a new content drop, and I often got confused about update times due to timezones. To solve this, I created a new minisite.\n\nThe site is available at forza.jakelee.co.uk.\n\nIt is very intentionally functionality-first, so don’t expect any fancy design ideas here! Here’s how it looks:\n\n\n\nHow it works\n\nAll the code used for the site is public (forza.js specifically), and it is honestly mostly from StackOverflow.\n\nEvery function that is adapted from a StackOverflow answer is credited, but here is a complete list:\n\n\n  Creating a date for a specific day each week.\n  Displaying a countdown to a date.\n  Calculating weeks between 2 dates.\n  Adding days to a date\n\n\nThe functions are self-explanatory, and even a not-very-good JavaScript programmer like myself can eventually figure out how they work! For example, this function (from StackOverflow) works out when the next season starts (next Thursday at 14:30 GMT):\n\nfunction getNextSeasonStart(d = new Date()) {\n    let thursday = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate() + (4 - d.getDay()), 14, 30, 0, 0));\n    thursday &lt;= d ? thursday.setDate(thursday.getDate() + 7) : null;\n    return thursday;\n}\n\n\nPlans\n\nI’d like to expand on the site eventually to have an actual design besides GitHub Pages’ default. For now though, it’s “good enough”.\n\nAdditionally, currently I have to manually update the new series’ title once per month. Ideally this would be automated, but I am not particularly interested in parsing the Forza team’s news posts!\n\nIt would be interesting to incorporate new car unlocks &amp; purchasable DLC into the site, but since they’re so unpredictable I’m unsure how to do it efficiently. For now, the useful links to other resources will have to be enough.\n\nConclusion\n\nOverall I’m happy enough with the site, and I’ll likely use it each week to check when I’ll receive an update due to shifting timezones. I was surprised how easy timezones were to work with in Javascript (once I discovered Date.UTC), and this was a good chance to play with basic math and date functionality.\n\nOne last time, the site is at forza.jakelee.co.uk.\n"
    } ,
  
    {
      "tags"     : "Android, Drawable, Crashes",
      "title"    : "Identifying and fixing a DisplayListCanvas crash (too large bitmap) with none of my Android code in the stacktrace",
      "excerpt"  : "A project recently had a crash that had been reported in low numbers for the lifetime of the app. Interestingly, the stack trace was unchanging, but only displayed “android.” code, nothing from my codebase! Here’s how I debugged it and found a fix (hint: it’s caused by drawables).\n",
      "url"      : "/displaylistcanvas-crash-with-no-codebase-references/",
      "date"     : "Sep 5, 2023",
      "content"  : "A project recently had a crash that had been reported in low numbers for the lifetime of the app. Interestingly, the stack trace was unchanging, but only displayed “android.” code, nothing from my codebase! Here’s how I debugged it and found a fix (hint: it’s caused by drawables).\n\nThis article is going to be as much about the bug hunting process as the fix, so if you just want to fix your codebase jump straight to the solution!\n\nBug hunting\n\nThe first thing to look at with an unusual crash is the stack trace, to see if there are any clues.\n\nStack trace\n\nMy crash’s stack trace did not reference any lines of my code. It consisted of a lot of view related code eventually calling some sort of image displaying logic:\n\nFatal Exception: java.lang.RuntimeException: Canvas: trying to draw too large(177707520bytes) bitmap.\n       at android.view.DisplayListCanvas.throwIfCannotDraw(DisplayListCanvas.java:229)\n       at android.view.RecordingCanvas.drawBitmap(RecordingCanvas.java:97)\n       at android.graphics.drawable.BitmapDrawable.draw(BitmapDrawable.java:529)\n       at android.widget.ImageView.onDraw(ImageView.java:1367)\n       at android.view.View.draw(View.java:20373)\n       at android.view.View.updateDisplayListIfDirty(View.java:19318)\n       at android.view.View.draw(View.java:20096)\n       at android.view.ViewGroup.drawChild(ViewGroup.java:4421)\n       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4207)\n       at androidx.constraintlayout.widget.ConstraintLayout.dispatchDraw(ConstraintLayout.java:1975)\n       at android.view.View.draw(View.java:20376)\n       at android.view.View.updateDisplayListIfDirty(View.java:19318)\n... 50+ lines of view related code removed ...\n       at android.os.Looper.loop(Looper.java:164)\n       at android.app.ActivityThread.main(ActivityThread.java:6944)\n       at java.lang.reflect.Method.invoke(Method.java)\n       at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)\n       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)\n\n\nAlright, so it’s… a massive image somewhere in the app. This is not particularly helpful.\n\nWhat other information do we have available?\n\nGathering clues\n\nIs it repeatable?\n\nFirst up, does it seem repeatable or a bizarre edge case? Looking at Crashlytics (other platforms will show similar data), we can see 40 users affected in the past 3 months, with a total of 169 crashes:\n\n\n\nWhilst these are relatively low numbers, ~4.2 crashes per user suggests these users are in a permanently broken state, and restarting the app is not fixing the problem. This is obviously bad for the user, but good for us trying to reproduce and fix it!\n\nWho is affected?\n\nNext up, who is it affecting?\n\n\n\nAh! Everyone is on Android 8! This is definitely a useful clue, but we will hang onto it for now.\n\nWhat were the users doing?\n\nDue to the stack trace not mentioning our code, we don’t know where the crash happens. However, even with basic log events being sent to Crashlytics (e.g. screen opened), we can find out!\n\n\n\nAlright, I now know the approximate screen the user was on, and what they had done beforehand. I also looked at various crashes, and they all had different paths to the same destination, telling me the screen itself is likely the issue.\n\nAny other information?\n\nSo, we now know which screen causes the crash for Android 8 users. Just so we don’t forget, we also have a consistent image size between all the crashes (177707520 bytes), telling us it’s something constant (e.g. not a profile picture).\n\nThat number will be important later!\n\nReproducing the bug\n\nFirst thing to do is open up an Android 8 emulator, and go to that screen! As expected, it didn’t crash. However, that screen has multiple states, and after trying a few I found the exact scenario that crashed. Every single time I tried to open a specific type of receipt, the app would crash, leaving only that mysterious stack trace in Logcat.\n\nUsually with a bug, reproducing it is over half the battle. However this time, I could not work out why the app crashed! I commented out all image loading code, set breakpoints all over the place, tried drastic steps like detaching ViewModels, and no luck. It would always crash when opened.\n\nIsolating the bug\n\nThen I realised… the crash mentions views. So… what’s in the XML? Initially I tried removing the logos, header images, anything dynamic. Still crashed. Then I noticed this section:\n\n&lt;ImageView\n            android:layout_width=\"0dp\"\n            android:layout_height=\"wrap_content\"\n            android:scaleType=\"centerCrop\"\n            android:src=\"@drawable/ic_gradient_white_circles\"\n\n\nHuh, I don’t remember a white circles icon, and certainly not one with a gradient. I wonder what the file looks like?\n\n\n\nUh oh. There’s 3 relatively minor issues here, which combine to make a big issue:\n\n\n  This decorative background gradient should be XML.\n  If it has to be a PNG, it should not be 485 KB!\n  If it has to be a big PNG, it should definitely not be in the drawable folder! That’s for XML!\n\n\nReplacing this image in the XML stops the crash, confirming our theory that it is problematic. However, we can also confirm it through maths…\n\nConfirming the cause\n\nRemember the number 177707520 from our stack trace? Time to see where that comes from:\n\n\n  Our image has a resolution of 1440*3428. This is 4,936,320 pixels.\n  Our test device is XXHDPI density, and since the image is placed in the drawable folder, it gets scaled up 3x (source) to fit the screen (despite the already large size!)\n  This gives us a resolution of (1440*3)*(3428*3), or 78,981,120 pixels. This is a lot.\n  Our lossless, transparency-supporting PNG needs 4 bytes per pixel (alpha, red, green, blue). 78,981,120*4 = 177,707,520 bytes needed.\n  That’s the number we started with! So yes, this image is 100% the cause of the crash.\n\n\nThe solution\n\nThe problem can be solved in many ways, as it is a combination of multiple minor issues:\n\n\n  Replace the PNG with XML: The correct fix, but may be high effort.\n  Replace the PNG with multiple scaled versions: Also a good fix, if XML isn’t possible.\n  Replace the PNG with a JPG / GIF: This might stop the crash occurring (although probably not due to the scaling still happening), but would still use up extra memory unnecessarily.\n  Move the PNG out of drawable into drawable-nodpi: Will stop the image being scaled absurdly, but will also result in some devices loading larger images than necessary.\n\n\nI ended up going for solution 4 as an immediate fix, with solutions 1 &amp; 2 planned for this &amp; other currently unscaled drawables. I also discovered we have a couple of hundred country flags in our drawable folder, so they got moved too! Always fun raising a PR with hundreds of changes, yet zero additions or deletions.\n\n\n\nDrawable folders\n\nThe drawable folders are a constant source of confusion for Android devs, even experienced ones. This isn’t helped by the official docs stating the oddly misleading:\n\n\n  To use an image resource, add your file to the res/drawable/ directory of your project.\n\n\nIn reality, any PNG / JPG / GIFs put in /drawable/ get treated as /drawable-mdpi/, which is almost certainly not what a developer intends (more info).\n\nThe core rules for real-world usage are simple:\n\n\n  XML files are put in /drawable/.\n  PNG files get scaled to multiple sizes and put in /drawable-xhdpi/, /drawable-xxhdpi/, etc.\n  Anything that shouldn’t be scaled (rare!) goes in /drawable-nodpi/.\n\n\nConclusion\n\n\n  Use all the clues available when investigating a crash. Repeat occurrences, actions beforehand, OS used, as well as of course the stack trace.\n  If your stack trace only seems to mention views and layouts, the problem is in your views and layouts!\n  PNG / JPG should never be in the drawable folder. Ever.\n\n"
    } ,
  
    {
      "tags"     : "YouTube, GitHub Actions",
      "title"    : "Introducing \"The Yogscast List™️\", a list of 100+ Yogscast-y YouTube channels 📺",
      "excerpt"  : "A couple of weeks ago I created a list of Jerma fan channels, as there’s a pretty obsessive fanbase. Since The Yogscast has 30+ members, there’s a lot more original content coming out, making them an excellent candidate for a similar project!\n",
      "url"      : "/list-of-yogscast-youtube-channels/",
      "date"     : "Aug 30, 2023",
      "content"  : "A couple of weeks ago I created a list of Jerma fan channels, as there’s a pretty obsessive fanbase. Since The Yogscast has 30+ members, there’s a lot more original content coming out, making them an excellent candidate for a similar project!\n\nThe project is of course open source again, and can be accessed at: yogscast.jakelee.co.uk\n\nIt seems to be going down fairly well on the Yogscast subreddit, hopefully the community finds it useful. Enjoy!\n"
    } ,
  
    {
      "tags"     : "YouTube, GitHub Actions, Shell, Bash",
      "title"    : "Building a GitHub Actions script to fetch metadata from multiple YouTube channels, and save it into a Markdown file",
      "excerpt"  : "I recently created a list of Jerma fan channels, and have now added automatically updating channel statistics! This requires interacting with YouTube’s API, parsing JSON, writing Markdown, merging files and more, so here’s a full guide to building something similar.\n",
      "url"      : "/fetching-youtube-metadata-in-github-actions-and-persisting/",
      "date"     : "Aug 19, 2023",
      "content"  : "I recently created a list of Jerma fan channels, and have now added automatically updating channel statistics! This requires interacting with YouTube’s API, parsing JSON, writing Markdown, merging files and more, so here’s a full guide to building something similar.\n\nNote: A super-summarised version of this post (without any explanations) appeared on Code Review Stack Exchange. Additionally, the site was previously at jerma.jakelee.co.uk before moving to channels.jerma.io.\n\nObjective\n\nSo, what am I trying to create? Ultimately, a way to convert a list of YouTube channels into a Markdown file with channel statistics, and I want this list to update both on demand and on a schedule.\n\nBefore I dive into the technical details, here’s all the code in case you want to skip the words:\n\n\n  GitHub Actions workflow\n  YouTube metadata bash script\n\n\nAnd some relevant inputs / outputs:\n\n\n  Console log of the script executing\n  Example channel list\n  Example template\n  Example output file\n\n\nPrep work\n\nI’m going to use GitHub Actions for my script, and perform this series of steps:\n\n\n  Pull down the repo.\n  Update YouTube channel stats:\n    \n      Parse a list of YouTube channel IDs and nicknames.\n      Fetch their metadata via YouTube’s Channel API.\n      Build up Markdown tables using this metadata.\n      Load a Markdown template, and replace a placeholder with the generated Markdown.\n    \n  \n  Save these changes.\n\n\nBefore we build our script however, we need to generate an API key, and have the ability to actually run the script on GitHub Actions!\n\nAccessing YouTube API\n\nYouTube’s official API guide1 is a great resource, and I’ll just be providing more specific steps here.\n\n\n  Open Google Developer Console2 and create a new project.\n  With this project selected, go to Credentials3 and Create Credentials -&gt; API key.\n  Go to the API Library4, search YouTube Data API v35, and click Enable.\n  Once created, click Edit API key (on Credentials screen)\n    \n      Give it a sensible name.\n      Set an API restriction to YouTube Data API v3.\n    \n  \n\n\n\n\nThat’s it! You now have an API key that is relatively safe (as it can only be used for YouTube), ready to store securely in GitHub and fetch YouTube data with.\n\nIt’s worth pointing out that Google recommends6 restricting who can use this API key. Unfortunately GitHub Actions uses thousands of (occasionally changing) IP addresses7, so whitelisting them all is not viable!\n\nPreparing GitHub Action\n\nI won’t go through the basics of making a GitHub repo (although GitHub has a guide8), and will assume it already exists.\n\nAdding GitHub secret\n\nWe’re going to add our new API key as a GitHub Action secret, so that the CI can access it without it being in plaintext. Under your repo’s Settings, navigate to Security -&gt; Secrets and variables -&gt; Actions, then New repository secret.\n\nGive your secret a simple name (e.g. API_KEY), put the key itself under Secret, and add it.\n\n\n\nBasic workflow setup\n\nNext, we need to make a workflow9 to actually trigger our upcoming code.\n\nTo do this, create a YAML config file inside .github/workflows/ called something intuitive like metadata-update.yml. Here is mine.\n\nBefore adding any steps, we need some basic framework to be able to run the workflow manually (workflow_dispatch), schedule it (schedule: cron), and have the ability to edit our own code (permissions):\n\non:\n  schedule:\n    - cron: '0 8 * * *'\n  workflow_dispatch:\n\njobs:\n  metadata-update:\n    runs-on: ubuntu-latest\n    permissions:\n      contents: write\n    steps:\n\n\nIt won’t actually do anything yet, but it is now technically a functional job called metadata-update.\n\nFurther workflow setup\n\nNow time to add some actually useful steps! Just underneath the code added in the previous section, we need to add 3 steps:\n\n1: Checkout a few files we need with GitHub’s actions/checkout10. For this repo sparse-checkout11 doesn’t save much time, but on a large repo it would help massively.\n\n    - name: Checkout channel config file\n      uses: actions/checkout@v3.5.3\n      with: \n        sparse-checkout: |\n          automation/*\n          README.md\n        sparse-checkout-cone-mode: false\n\n\n2: Run our script (./automation/youtube.sh) to perform all our tasks. We do chmod +x beforehand so we can execute the script, and configure both the API_KEY and WORKSPACE so our script has access to them.\n\n    - name: Update YouTube data\n      run: |\n        chmod +x ./automation/youtube-update.sh\n        ./automation/youtube-update.sh\n      env:\n          API_KEY: ${{ secrets.API_KEY }}\n          WORKSPACE: ${{ github.workspace }}\n\n\n3: Save the changes to the fetched metadata (stored in README.md) using git-auto-commit-action12. Note that I have intentionally configured the commit_author to not be me, by default it will use whoever triggered the workflow.\n\n    - name: Save changes\n      uses: stefanzweifel/git-auto-commit-action@v4\n      with:\n        commit_message: Updated YouTube statistics\n        commit_author: GitHub Actions &lt;actions@github.com&gt;\n        file_pattern: 'README.md'\n\n\nOnce we put all those parts together, we end up with a functional metadata-update.yml file.\n\nBash script\n\nAs a reminder, our script will convert a list of channels into a table of channels with metadata. It will also allow displaying an arbitrary emoji (e.g. for “best” channels).\n\nFor example, our input of:\n\n#### Stream Archives\nUC2oWuUSd3t3t5O3Vxp4lgAA;2018-streams;🐶\nUC4ik7iSQI1DZVqL18t-Tffw;2016-2018streams\nUCjyrSUk-1AGjALTcWneRaeA;2016-2017streams\n\n\nshould result in an output of:\n\n#### Stream Archives\n\n| Channel | # Videos | Subscribers | Views |\n| --- | --- | --- | --- |\n| 🐶[Jerma Stream Archive](https://youtube.com/@jermastreamarchive) | 770 | 274K | 88M |\n| [Ster/Jerma Stream Archive](https://youtube.com/@sterjermastreamarchive) | 972 | 47K | 20M |\n| [starkiller201096x](https://youtube.com/@starkiller201096x) | 79 | 2.9K | 1.5M |\n\n\nCreating script file\n\nFirst, we need to make a bash file to actually run! Create your .sh file wherever you defined in step 2 above, I chose /automation/youtube-update.sh.\n\nParsing channel list\n\nWe have a plain text list of channels (channels.txt), with 2 types of data:\n\n  Headers, in plain Markdown format (e.g. ### Title).\n  Channels, in the format channel ID;nickname;emoji, where emoji is optional.\n\n\nReading the file is basically just “while there are lines left, parse them”:\n\nHEADER_PREFIX=\"#### \"\nOUTPUT=\"\"\nwhile read -r LINE; do\n    if [[ ${LINE} == ${HEADER_PREFIX}* ]]; then\n        echo \"Adding header ${LINE}\"\n        OUTPUT=\"${OUTPUT}\\n${LINE}\\n\\n\"\n        OUTPUT=\"${OUTPUT}| Channel | # Videos | Subscribers | Views |\\n| --- | --- | --- | --- |\\n\"\n    else\n        # Skipped for now\n    fi\ndone &lt; \"${WORKSPACE}/automation/channels.txt\"\n\n\nWe’re finding header lines by just looking if they start with our HEADER_PREFIX string. If they are, we output the header, then create a Markdown table header, ready to populate with rows (1 per channel).\n\nNote that OUTPUT is a constantly added to variable used to store the full Markdown data.\n\nCalling YouTube API\n\nInside the else branch above, we first need to split our semicolon separated LINE into an ARRAY_LINE array of 2-3 items (due to optional emoji):\n\n        IFS=';' read -r -a ARRAY_LINE &lt;&lt;&lt; \"${LINE}\"\n\n\nNext, we output the channel ID ([0]) and nickname ([1]) to our logs, and use the ID (along with our API key from earlier) to call YouTube’s channel API and save the results to output.json:\n\n        echo \"Adding channel ${ARRAY_LINE[1]} (${ARRAY_LINE[0]})\"\n        curl \"https://youtube.googleapis.com/youtube/v3/channels?part=statistics,snippet&amp;id=${ARRAY_LINE[0]}&amp;key=${API_KEY}\" \\\n            --header 'Accept: application/json' \\\n            -fsSL -o output.json\n\n\nLuckily YouTube’s channels API13 is very well documented and easy to use, and -fsSL is just a helpful curl config. We’re going to be fetching the statistics and snippet parts of the API, which will return JSON containing these key fields (irrelevant ones omitted):\n\n{\n  \"pageInfo\": {\n    \"totalResults\": 1\n  },\n  \"items\": [\n    {\n      \"snippet\": {\n        \"title\": \"Google for Developers\",\n        \"customUrl\": \"@googledevelopers\"\n      },\n      \"statistics\": {\n        \"viewCount\": \"234466180\",\n        \"subscriberCount\": \"2300000\",\n        \"videoCount\": \"5807\"\n      }\n    }\n  ]\n}\n\n\nParsing JSON\n\nNow that our useful data has been saved to output.json, we need to make it useful and parse it!\n\nFirst, I make sure we have exactly 1 response by looking for the totalResults. If any error or unexpected behaviour is encountered, this is where it will be caught:\n\n        if [[ $(jq -r '.pageInfo.totalResults' output.json) == 1 ]]; then\n            # Skipped for now, see next code block!\n        else\n            echo \"Failed! Bad response received: $(&lt;output.json)\"\n            exit 1\n        fi\n\n\nIf a single channel is returned, then we can pull out the useful data from output.json using jq14 and prepare our Markdown table row:\n\n            TITLE=$(jq -r '.items[0].snippet.title' output.json)\n            URL=$(jq -r '.items[0].snippet.customUrl' output.json)\n            VIDEO_COUNT=$(jq -r '.items[0].statistics.videoCount' output.json | numfmt --to=si)\n            SUBSCRIBER_COUNT=$(jq -r '.items[0].statistics.subscriberCount' output.json | numfmt --to=si)\n            VIEW_COUNT=$(jq -r '.items[0].statistics.viewCount' output.json | numfmt --to=si)\n            echo \"Added ${TITLE}: ${VIDEO_COUNT} videos (${VIEW_COUNT} views)\"\n            OUTPUT=\"${OUTPUT}| ${ARRAY_LINE[2]}[${TITLE}](https://youtube.com/${URL}) | ${VIDEO_COUNT} | ${SUBSCRIBER_COUNT} | ${VIEW_COUNT} |\\n\"\n\n\nSome of these outputs (e.g. VIEW_COUNT) are then passed to numfmt15 to make them “pretty” (e.g. 2400 -&gt; 2.4K). All the values are then used to build a self-explanatory row of data in Markdown format.\n\nNote that currently the script inefficiently parses the JSON 5x. I intend to improve this, but as this script is very short and rarely run it is not urgent.\n\nSaving data\n\nOkay! So OUTPUT now contains lots of headers, and Markdown tables with lots of statistics. How do we do something useful with this?\n\nI chose to use a placeholder file (with dynamic-channel-data being replaced by the list of channels), with the output replacing the repository’s README.md. This is surprisingly easy in bash:\n\n# Replace placeholder in template with output, updating the README\nTEMPLATE_CONTENTS=$(&lt;\"${WORKSPACE}/automation/template.md\")\necho -e \"${TEMPLATE_CONTENTS//${PLACEHOLDER_TEXT}/${OUTPUT}}\" &gt; \"${WORKSPACE}/README.md\"\n\n# Debug\ncat \"${WORKSPACE}/README.md\"\n\n\nAll we’re doing is loading up the template ($(&lt;file)), replacing PLACEHOLDER_TEXT with our OUTPUT, and sending the output to README.md. Finally, the script outputs the contents of README.md so that there’s a copy in the logs.\n\nPutting it all together\n\nAll done! Here’s the final script, with API_KEY and WORKSPACE being environment variables:\n\n#!/bin/bash\n\nHEADER_PREFIX=\"#### \"\nPLACEHOLDER_TEXT=\"dynamic-channel-data\"\nOUTPUT=\"\"\n\n# Convert list of channels into Markdown tables\nwhile read -r LINE; do\n    if [[ ${LINE} == ${HEADER_PREFIX}* ]]; then\n        echo \"Adding header ${LINE}\"\n        OUTPUT=\"${OUTPUT}\\n${LINE}\\n\\n\"\n        OUTPUT=\"${OUTPUT}| Channel | # Videos | Subscribers | Views |\\n| --- | --- | --- | --- |\\n\"\n    else\n        IFS=';' read -r -a ARRAY_LINE &lt;&lt;&lt; \"${LINE}\" # Split line by semi-colon\n        echo \"Adding channel ${ARRAY_LINE[1]} (${ARRAY_LINE[0]})\"\n        curl \"https://youtube.googleapis.com/youtube/v3/channels?part=statistics,snippet&amp;id=${ARRAY_LINE[0]}&amp;key=${API_KEY}\" \\\n            --header 'Accept: application/json' \\\n            -fsSL -o output.json\n\n        # Pull channel data out of response if possible\n        if [[ $(jq -r '.pageInfo.totalResults' output.json) == 1 ]]; then\n            TITLE=$(jq -r '.items[0].snippet.title' output.json)\n            URL=$(jq -r '.items[0].snippet.customUrl' output.json)\n            VIDEO_COUNT=$(jq -r '.items[0].statistics.videoCount' output.json | numfmt --to=si)\n            SUBSCRIBER_COUNT=$(jq -r '.items[0].statistics.subscriberCount' output.json | numfmt --to=si)\n            VIEW_COUNT=$(jq -r '.items[0].statistics.viewCount' output.json | numfmt --to=si)\n            echo \"Added ${TITLE}: ${VIDEO_COUNT} videos (${VIEW_COUNT} views)\"\n            OUTPUT=\"${OUTPUT}| ${ARRAY_LINE[2]}[${TITLE}](https://youtube.com/${URL}) | ${VIDEO_COUNT} | ${SUBSCRIBER_COUNT} | ${VIEW_COUNT} |\\n\"\n        else\n            echo \"Failed! Bad response received: $(&lt;output.json)\"\n            exit 1\n        fi\n    fi\ndone &lt; \"${WORKSPACE}/automation/channels.txt\"\n\n# Replace placeholder in template with output, updating the README\nTEMPLATE_CONTENTS=$(&lt;\"${WORKSPACE}/automation/template.md\")\necho -e \"${TEMPLATE_CONTENTS//${PLACEHOLDER_TEXT}/${OUTPUT}}\" &gt; \"${WORKSPACE}/README.md\"\n\n# Debug\ncat \"${WORKSPACE}/README.md\"\n\n\nLessons learned\n\nBash\n\nMy bash / shell knowledge is pretty weak. I don’t write any local automation / scripts, and only interact with it for CI things like this, so I’ve always found it painful and unintuitive to work with.\n\nHowever, making a useful script like this has definitely made me appreciate how easy it makes tasks that would be awful in other languages. For example, loading the contents of a file into a variable is just… $(&lt;file). Sure, I bet it doesn’t work perfectly for all situations, but realistically when programming you usually just want super simple “default” syntax.\n\nI also really appreciated how easy it was to pass data between utilities, and how useful these utilities could be. When I wanted to make numbers human-readable (e.g. “2.5M”), I initially got lost in a rabbit hole of writing a helper function, doing string manipulation, etc. Then, by sheer chance, this Stack Exchange question came up mentioning “convert … to human-readable”, and I discovered numfmt exists! It does exactly what I want, is built-in, yet none of the 10+ answers about number formatting mentioned it whatsoever.\n\nI can’t entirely explain why it took so long for me to find numfmt. Perhaps the primary fault is with me assuming I’d have to solve it myself, so looking for manual solutions instead. However, a large part of the issue is with every bash related answer either:\n\n  Saying “use x”, with either no extra information, or an extensive argument in comments about why other options were better.\n  Giving a comprehensive “use x if y, or z if a, but only use b if cde is true” style answer. For example, this semi-related answer actually included the numfmt information I wanted, but it was so lengthy and caveat-filled that I just didn’t read it.\n\n\nShellcheck\n\nShellcheck exists! It’s a super simple utility available as a website or package that tells you why your code sucks, basically providing linting. This helped me make a few simple improvements to my script around string escaping, and provided justifications for everything (e.g. why ${OUTPUT} is significantly better than OUTPUT).\n\nYouTube API quirk\n\nWhilst YouTube’s Channel API13 is great, as is the ability to make test calls in the browser, it has a weird quirk. Searching by username… doesn’t seem to work half the time? I’m not sure if this is due to channel size or something else, but around 50% of the channel names simply returned 0 results. The documentation provides no explanation for this, just:\n\n\n  The forUsername parameter specifies a YouTube username, thereby requesting the channel associated with that username.\n\n\nLuckily, searching by id worked perfectly, and has the added benefit of never changing. It could also (one day) be used to look up multiple channels at once:\n\n\n  The id parameter specifies a comma-separated list of the YouTube channel ID(s) for the resource(s) that are being retrieved. In a channel resource, the id` property specifies the channel’s YouTube channel ID.\n\n\nQuotas\n\nGitHub Actions and YouTube have generous free quotas!\n\nWhilst I do have a GitHub Pro plan, the CI time per month is only 3,000 vs 2,000 for a free plan16. Since the script takes under a minute for the current channel list, and runs once a day, we’re using ~1% of the free quota. Oddly enough, my usage statement17 (even the raw downloadable CSV) shows 0 minutes used so far this month, not sure why:\n\n\n\nFor YouTube, you can make 10k requests per day for free. Considering each channel lookup only counts as 1, this is way more than we need! This opens up the possibility of fetching the latest / most popular video for each channel in the future.\n\n\n\nError handling\n\nCurrently, my script has basically no error handling, and if anything goes wrong just throws an error and gives up.\n\nWhilst this might seem like a flaw, it’s by design. As a failed run doesn’t make the data any less valid, just slightly out of date, that is massively preferable to a corrupted run with invalid outputs. Additionally, I automatically a recieve an email on failed builds, so I can just rely on this to let me know if any channels have been deleted or other errors have occurred.\n\nConclusion\n\nIn conclusion, this was a very fun mini project! I learned a lot about GitHub Actions and Bash, both of which I wanted to get better at.\n\nWhilst the actual project is obviously a little silly, I like the idea of turning random hobbies into useful tools for others. This also gives me an automated tool that I can use if I want to try GitHub Actions features in the future, and has plenty of additional functionality that could be implemented.\n\nI was pretty impressed with how simple GitHub Actions was to use, with even spurious ideas (“hey can I only fetch the required files?”) being well documented and easy to implement. The “auto-commit” library was also impressive (and seems well maintained), with default functionality working exactly as expected, yet also having the ability to customise it to my requirements.\n\nFinally, this writing up of how the script works is mostly to remind myself about bash. I know when I try and do something else CI-related in 6 months I’ll be confused by the syntax, so hopefully this post will remind me that I briefly understood it once!\n\nOne last time, the results of this article are available at channels.jerma.io.\n\nReferences\n\n  \n    \n      https://developers.google.com/youtube/v3/getting-started &#8617;\n    \n    \n      https://console.developers.google.com/ &#8617;\n    \n    \n      https://console.developers.google.com/apis/credentials &#8617;\n    \n    \n      https://console.cloud.google.com/apis/library/browse &#8617;\n    \n    \n      https://console.cloud.google.com/apis/library/youtubeanalytics.googleapis.com &#8617;\n    \n    \n      https://cloud.google.com/docs/authentication/api-keys#api_key_restrictions &#8617;\n    \n    \n      https://api.github.com/meta &#8617;\n    \n    \n      https://docs.github.com/en/get-started/quickstart/create-a-repo &#8617;\n    \n    \n      https://docs.github.com/en/actions/using-workflows &#8617;\n    \n    \n      https://github.com/actions/checkout &#8617;\n    \n    \n      https://git-scm.com/docs/git-sparse-checkout &#8617;\n    \n    \n      https://github.com/stefanzweifel/git-auto-commit-action &#8617;\n    \n    \n      https://developers.google.com/youtube/v3/docs/channels/list &#8617; &#8617;2\n    \n    \n      https://jqlang.github.io/jq/manual/ &#8617;\n    \n    \n      https://www.gnu.org/software/coreutils/manual/html_node/numfmt-invocation.html &#8617;\n    \n    \n      https://docs.github.com/en/billing/managing-billing-for-github-actions/about-billing-for-github-actions#included-storage-and-minutes &#8617;\n    \n    \n      https://github.com/settings/billing#usage &#8617;\n    \n  \n\n"
    } ,
  
    {
      "tags"     : "Jerma, YouTube",
      "title"    : "Introducing \"The Jerma List™️\", a list of 70+ Jerma-related YouTube channels 📺",
      "excerpt"  : "As anyone could probably figure out from my thousands of YouTube video views and hundreds of hours on Twitch, I’m a big fan of Jerma985. Since there’s… hundreds of fan channels, it’s easy to miss some amazing content, so I created a complete(ish) list!\n",
      "url"      : "/jerma-fan-channel-list/",
      "date"     : "Aug 7, 2023",
      "content"  : "As anyone could probably figure out from my thousands of YouTube video views and hundreds of hours on Twitch, I’m a big fan of Jerma985. Since there’s… hundreds of fan channels, it’s easy to miss some amazing content, so I created a complete(ish) list!\n\nIt’s at jerma.jakelee.co.uk channels.jerma.io.\n\nSince it’s just a simple GitHub pages site &amp; open-source (repo repo), hopefully others add channels too, otherwise… I’ll look a little bit obsessed. Oops.\n\nThere’s also links to 4 Jerma games, and all kinds of bizarre soundboards / tools / utilities. Eventually I might hook it up to a GitHub Action using YouTube’s API to update the video &amp; subscriber counts, but that’s only worth the time investment if it becomes a useful resource.\n\nEdit: I did hook this up to a GitHub Action! A full write-up has now been published.\n\nAnyway, enjoy!\n"
    } ,
  
    {
      "tags"     : "Markdown, CSS",
      "title"    : "Different approaches to conversation transcript formatting in Markdown 🗣️✍️",
      "excerpt"  : "I’m currently trying to write some fiction, and conversation transcripts are a key part of this. However, there doesn’t seem to be any standard way of displaying a conversation transcript in Markdown, with plain text looking pretty ugly! Here’s a few approaches, and my recommendation.\n",
      "url"      : "/markdown-conversation-formatting/",
      "date"     : "Aug 4, 2023",
      "content"  : "I’m currently trying to write some fiction, and conversation transcripts are a key part of this. However, there doesn’t seem to be any standard way of displaying a conversation transcript in Markdown, with plain text looking pretty ugly! Here’s a few approaches, and my recommendation.\n\nTo compare approaches, I’ll use a short exchange about stock trading from one of my favourite underrated films of all time: Primer. Here’s the conversation in plain text, as you can see it doesn’t stand out much, and is quite basic:\n\n\n\nAaron: What do they do?\n\nAbe: What do you mean?\n\nAaron: What does it, what does this company do? Do they make things or…\n\nAbe: I don’t know. It doesn’t matter. All that matters is that the price goes up. You know, and the volume is so high that the number of shares we’re trading is not going to affect the price.\n\nAaron: You really don’t know what they do?\n\n\n\nMarkdown\n\nOne of the main reasons I write in Markdown instead of HTML or writing a Google Doc is for the ease of minor styling. I can make text italic or bold without taking my hands off the keyboard, or make a list etc.\n\nWith this in mind, however conversations are formatted must be easy to work with, with minimal wasted keystrokes / clicks. Here’s a few approaches.\n\nBasic syntax\n\nWhat about the obvious approach that was used at the start of this post? One line per message, and a blank line between messages so that Markdown adds a space.\n\nWell, it’s definitely easy to use (besides having to press enter twice for a new line), but personally I think this might be too much vertical spacing. The spacing is suitable for paragraphs, for a short message it seems like overkill. The line height can be adjusted, but at least with default spacing it’s a bit too tall. Additionally, the character names aren’t distinguished at all, nor is the fact that it’s a quote.\n\nThis also has the disadvantage of making the markdown file about twice as long as it needs to be, a fact that will probably become pretty annoying when editing hundreds of lines of conversation.\n\nAaron: What do they do?\n\nAbe: What do you mean?\n\nAaron: What does it, what does this company do? Do they make things or...\n\nAbe: I don't know. It doesn't matter. All that matters is that the price goes up. You know, and the volume is so high that the number of shares we're trading is not going to affect the price.\n\nAaron: You really don't know what they do?\n\n\nList of messages\n\nWe can reduce the vertical space between transcript messages by making them each list items. This also has the advantage of keeping one line per message in the markdown file, with the disadvantage of completely unnecessary bullet points taking up space.\n\n\n  Aaron: What do they do?\n  Abe: What do you mean?\n  Aaron: What does it, what does this company do? Do they make things or…\n  Abe: I don’t know. It doesn’t matter. All that matters is that the price goes up. You know, and the volume is so high that the number of shares we’re trading is not going to affect the price.\n  Aaron: You really don’t know what they do?\n\n\n* Aaron: What do they do?\n* Abe: What do you mean?\n* Aaron: What does it, what does this company do? Do they make things or...\n* Abe: I don't know. It doesn't matter. All that matters is that the price goes up. You know, and the volume is so high that the number of shares we're trading is not going to affect the price.\n* Aaron: You really don't know what they do?\n\n\nQuote &amp; bold\n\nHow about improving on an issue with the basic approach: No way to distinguish character names from the words they’ve said? Just making the character’s names bold should help with this, and putting them inside a block quote makes a bit more sense semantically (since the conversation is essentially a quote).\n\nUsing the appropriate tools (blockquote) for the conversation also means any automated tools can understand the messages a chat transcript. For example on this site, a solid indent is placed on the left, and all words are put in italics. These small stylistic additions are included by default in my site’s theme, with other platforms having similar included styles, and make it look much more like a quote!\n\nAdditionally, the bold tags mean the names and messages will be displayed differently in most text editors, making the writing / editing process slightly easier.\n\nNote: The indentation here has been improved by a later CSS change.\n\n  Aaron: What do they do?\n\n  Abe: What do you mean?\n\n  Aaron: What does it, what does this company do? Do they make things or…\n\n  Abe: I don’t know. It doesn’t matter. All that matters is that the price goes up. You know, and the volume is so high that the number of shares we’re trading is not going to affect the price.\n\n  Aaron: You really don’t know what they do?\n\n\n&gt; **Aaron**: What do they do?\n&gt;\n&gt; **Abe**: What do you mean?\n&gt;\n&gt; **Aaron**: What does it, what does this company do? Do they make things or...\n&gt;\n&gt; **Abe**: I don't know. It doesn't matter. All that matters is that the price goes up. You know, and the volume is so high that the number of shares we're trading is not going to affect the price.\n&gt;\n&gt; **Aaron**: You really don't know what they do?\n\n\nManual line breaks\n\nWhilst the block quotes work well, what about if we want our lines more compressed? We can manually add in HTML &lt;br&gt; at the end of each message. Turns out this really isn’t enough space between lines! The end result is very cramped, and adding the manual line breaks is a lot of effort. Not a good solution.\n\nAaron: What do they do?\nAbe: What do you mean?\nAaron: What does it, what does this company do? Do they make things or…\nAbe: I don’t know. It doesn’t matter. All that matters is that the price goes up. You know, and the volume is so high that the number of shares we’re trading is not going to affect the price.\nAaron: You really don’t know what they do?\n\n**Aaron**: What do they do?&lt;br&gt;\n**Abe**: What do you mean?&lt;br&gt;\n**Aaron**: What does it, what does this company do? Do they make things or...&lt;br&gt;\n**Abe**: I don't know. It doesn't matter. All that matters is that the price goes up. You know, and the volume is so high that the number of shares we're trading is not going to affect the price.&lt;br&gt;\n**Aaron**: You really don't know what they do?&lt;br&gt;\n\n\n2-column table\n\nOkay, I know this will be awful, but it’s an option for two-person conversations. It has the advantage of clearly showing both parties, and avoids typing out character names repeatedly, however the raw text is very hard to read. I wouldn’t recommend this whatsoever.\n\n\n  \n    \n      Aaron\n      Abe\n    \n  \n  \n    \n      What do they do?\n       \n    \n    \n       \n      What do you mean?\n    \n    \n      What does it, what does this company do? Do they make things or…\n       \n    \n    \n       \n      I don’t know. It doesn’t matter. All that matters is that the price goes up. You know, and the volume is so high that the number of shares we’re trading is not going to affect the price.\n    \n    \n      You really don’t know what they do?\n       \n    \n  \n\n\n| Aaron | Abe |\n| --- | --- |\n| What do they do? | |\n| | What do you mean? |\n| What does it, what does this company do? Do they make things or... | |\n| | I don't know. It doesn't matter. All that matters is that the price goes up. You know, and the volume is so high that the number of shares we're trading is not going to affect the price. |\n| You really don't know what they do? | |\n\n\nCSS styling\n\nAlright, so I’ve tried a few ways of formatting text using basic Markdown syntax. What about using CSS to find a solution, or improve an existing one?\n\nAlternating sides\n\nWhilst looking for a way to make the list of messages more conversation like, I found this StackOverflow solution that alternates the alignment of messages.\n\nFor short messages this isn’t too awful, and ends up looking like a 2-column table but with the ability to overlap. However, for longer messages it just becomes a mess.\n\nWhilst this could be improved by improving padding etc, a CSS reliant approach isn’t ideal. I actually couldn’t immediately get this working within my site’s style (hence the image), whereas a Markdown based solution will work far more reliably.\n\n\n\nSecond line indenting\n\nOne small change that can make dialogue far more readable whilst not becoming absolutely essential is indenting all lines except the first. This StackOverflow answer shows how 2 lines of CSS can make a massive difference:\n\n\n  \n    \n      Before\n      After\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nEven in this example the improvement is immediately obvious, in a conversation with longer messages this would be an eye-saver!\n\nGeneral avoidance\n\nI found quite a few very over-complicated solutions to styling a transcript, and I found it amazing how willing people are to have their text cluttered with classes everywhere! If the raw text isn’t readable, it’s going to be very painful to work with, and there’ll undoubtedly be styling errors here and there.\n\nAs such, I’m not sure any specific CSS should be used for displaying a conversation. Instead, the Markdown itself should be as simple yet semantically correct as possible, then the presentation can be changed all at once later on if desired.\n\nRecommendation\n\nI’m not sure any of the approaches I’ve looked at have been perfect. I love the simplicity of the basic syntax or list of messages, but the end result just isn’t good enough.\n\nDespite the slightly verbose syntax (&gt; &amp; **x**) of quote and bold, the aesthetically pleasing output seems better than any of the custom CSS heavy solutions I came across. Additionally, using HTML elements (blockquote) for their intended purposes can only have positive side effects in terms of SEO and accessibility! Whilst I’ll keep an eye out for syntax improvements, I think a blockquote and bold names is good enough.\n\nRecommendation usage\n\nI’ll add the **bold** asterisks as I type names, realistically it isn’t much more effort.\n\nFor adding the block quote &amp; empty lines it’s probably easier to wait until a section is done, and add them all at once, like so:\n\nNote: Make sure to turn off word wrap (Opt / Alt + Z in VSCode) before bulk editing lines.\n\n\n  \n    \n      Step\n      Example\n    \n  \n  \n    \n      Put the cursor at the start of the first line\n      \n    \n    \n      Hold Alt + Shift, then click the start of the last line\n      \n    \n    \n      Type &gt;, press enter, type &gt;, press space\n      \n    \n  \n\n\nFinally, here’s a slightly longer version of the sample quote (following the instructions above), to check it looks OK in longer conversations:\n\n\n\n  Aaron: What do they do?\n\n  Abe: What do you mean?\n\n  Aaron: What does it, what does this company do? Do they make things or…\n\n  Abe: I don’t know. It doesn’t matter. All that matters is that the price goes up. You know, and the volume is so high that the number of shares we’re trading is not going to affect the price.\n\n  Aaron: You really don’t know what they do?\n\n  Aaron: That’s why you were talking about a mid-cap fund, so the volume’d be high enough to hide us.\n\n  Abe: Yeah, yeah. Do you think that’s too cautious?\n\n  Aaron: I don’t know. I know there’s a lot of stocks out there that do a lot more than double, but this is my first day.\n\n"
    } ,
  
    {
      "tags"     : "GitHub, Markdown",
      "title"    : "Experimenting with GitHub's \"alert\" markdown syntax",
      "excerpt"  : "Back in May 2022, GitHub announced the ability to display “alerts” within Markdown documents on the site, by using a new syntax. These alerts originally only supported ℹ️ Notes and ⚠️ Warnings, however this week the 💬 Important category was added. Here’s how (and when) to use these alerts, and their limitations.\n",
      "url"      : "/github-alert-experiments/",
      "date"     : "Jul 30, 2023",
      "content"  : "Back in May 2022, GitHub announced the ability to display “alerts” within Markdown documents on the site, by using a new syntax. These alerts originally only supported ℹ️ Notes and ⚠️ Warnings, however this week the 💬 Important category was added. Here’s how (and when) to use these alerts, and their limitations.\n\nTypes of alert\n\nThere are 3 categories of alert (or “admonition”): Note, Important, and Warning. Each uses a different text, icon, and quote indicator colour, but with the same syntax:\n\n\n  [!NOTE]\nThis alert uses [!NOTE]\n\n\n\n  [!IMPORTANT]\nThis alert uses [!IMPORTANT]\n\n\n\n  [!WARNING]\nThis alert uses [!WARNING]\n\n\nAs these (obviously!) will only render correctly on GitHub itself, here’s a screenshot from each theme:\n\n\n  \n    \n      Variant\n      Light\n      Dark\n    \n  \n  \n    \n      Default\n      \n      \n    \n    \n      High contrast\n      \n      \n    \n  \n\n\nAll the colourblind themes seem to have no effect on the appearance of these alerts, although I’m glad to see high contrast variants have been added.\n\nWhen to use\n\nLuckily, these alert categories are (for now) pretty self-explanatory. The descriptions within the original post are perfect in my opinion, so they’re restated here:\n\n  Note: Highlights information that users should take into account, even when skimming.\n  Important: Crucial information necessary for users to succeed.\n  Warning: Critical content demanding immediate user attention due to potential risks.\n\n\nSyntax\n\nOriginally, these alerts used a weird combination of block quotes and bold text:\n\n&gt; **Note**\n&gt; This is a note\n\n\nHowever, it’s easy to see how someone could accidentally trigger this, which explains why the new bracket based syntax was added on the 21st July:\n\n&gt; [!NOTE]\n&gt; This is a note\n\n\nBoth syntaxes render identically, however the second “will gradually replace the old one”. Personally I find it a bit unusual that the feature hijacks the existing blockquote functionality, and isn’t built as a brand new piece of syntax. The [!NOTE] syntax reminds me of BBCode, which I thought died years ago!\n\nWhilst I do have my issues with the blockquote hijacking syntax, it does have the advantage of having a well defined set of rules to follow. For example, adding spaces after the [!NOTE] does nothing, whilst spaces before also does nothing… until there are enough to trigger a code block.\n\nI was intending to try and break this syntax by combining it with other elements, nesting the notes etc, but it looks like other users got there first! Within this comment thread, a few users do… quite impressive things to the syntax. Whilst it generally holds up well, there are inevitably a few quirks.\n\n\n\nConclusion\n\nWriting this post was tricky, since I had to write it directly on GitHub! Additionally, the alerts only appeared to preview correctly when creating a new file, and not when editing an existing one. This is perhaps to be expected for a beta feature, but still made it all feel a bit hacky.\n\nDespite my complaints, I do like the feature. I like that GitHub is trying to add new bits and pieces to Markdown (such as Mermaid last year), they are in the unique position to make a syntax standard by just implementing it. I also like the openness with the community, and seemingly exchanging views with both supporters and those with… surprisingly strong negative opinions. The development seems a little unusual, with silence since May 2022, then 3 updates at the end of July 2023! However, I hope there are more bits and pieces to come.\n\nFor example, eduardogerentklein suggested a ✅ Check syntax, which seems a simple yet useful addition, and would be great for confirming processes have been completed.\n\nWithin the original discussion, an excellent point is raised about localisation, and how this is currently only useful for English documents. I’m not sure if this can be solved easily, besides splitting out the appearance modifying term and the text displayed. Otherwise, every language’s variation will have to be defined as a keyword, and it’ll be unmanageable. A syntax like [!NOTE Nota] (for Spanish) would let the author customise the appearance.\n\nIf you’d like to contribute your opinions on GitHub’s alert feature, the original discussion is the best place.\n\nFinally, the product manager for this feature has a public test repository for it, so you can peek there if you want to be extremely up-to-date!\n"
    } ,
  
    {
      "tags"     : "Ruby, Jekyll",
      "title"    : "How to discover your Jekyll site's total word count, longest / shortest post, and more 🔡",
      "excerpt"  : "I’ve been writing blog posts for quite a few years, and when a single post can easily be thousands of words… my total word count must be in the hundreds of thousands! To find out, I expanded an existing Jekyll plugin’s functionality, here’s how to use it.\n",
      "url"      : "/calculating-jekyll-blog-word-count-and-more/",
      "date"     : "Jul 29, 2023",
      "content"  : "I’ve been writing blog posts for quite a few years, and when a single post can easily be thousands of words… my total word count must be in the hundreds of thousands! To find out, I expanded an existing Jekyll plugin’s functionality, here’s how to use it.\n\nThe plugin\n\nThe base of this post’s work is (author!) Matt Gemmell’s Jekyll-Posts-Word-Count plugin, who kindly merged in my many changes shortly after I raised them 🎉\n\nThe original plugin hasn’t had more than minor updates in 9 years(!), yet it still works perfectly. The beauty of simple, functional code, huh?\n\nInstallation\n\nIf you’re using GitHub Pages (as I am) for your Jekyll site, this plugin will not work remotely. However, locally anything goes.\n\n\n  Create a _plugins folder in your site’s base folder (if it doesn’t exist).\n  Open the posts-word-count.rb script, click ... in the top right, and select Download.\n  Move the downloaded file into your _plugins folder.\n\n\n\n\nThe plugin is installed! Now to use it…\n\nUsage\n\nThe plugin works via tags, with something like {% posts_word_count total %} giving the total word count.\n\nposts_word_count can (and usually should) be replaced with published_posts_word_count to exclude all draft posts.\n\ntotal can be replaced with quite a few different parameters:\n\n\n  total (total word count of all posts)\n  average (average word count across all posts)\n  total_characters (total character count of all posts)\n  average_characters (total average count of all posts)\n  longest (longest word count of any post)\n  longest_post_index (index in site.posts of longest post)\n  longest_post_title (title of longest post)\n  longest_post_url (url of longest post)\n  shortest (shortest word count of any post)\n  shortest_post_index (index in site.posts of shortest post)\n  shortest_post_title (title of shortest post)\n  shortest_post_url (url of shortest post)\n\n\nTo view all stats for a site (e.g. for the analysis below), you can use the following:\n\n### Totals\n\nTotal site words: {% published_posts_word_count total %} (average {% published_posts_word_count average %} per post)\n\nTotal site characters: {% published_posts_word_count total_characters %} (average {% published_posts_word_count average_characters %} per post)\n\n### Published post records \n\nLongest post: &lt;a href=\"{% published_posts_word_count longest_post_url %}\"&gt;{% published_posts_word_count longest_post_title %}&lt;/a&gt; ({% published_posts_word_count longest %} words)\n\nShortest post: &lt;a href=\"{% published_posts_word_count shortest_post_url %}\"&gt;{% published_posts_word_count shortest_post_title %}&lt;/a&gt; ({% published_posts_word_count shortest %} words)\n\n\nThis will (when deployed locally) show something like:\n\n\n\nMy stats\n\nProgramming site\n\n\n  Total site words: 152243 (average 945 per post)\n  Total site characters: 1767231 (average 10976 per post)\n  Longest post: Asynchronous Map Generator for Android (3661 words)\n  Shortest post: 2020’s essential Android development techniques (62 words)\n\n\n3.6k words in a single post!? The map generator writeup was my very first post on the site way back in 2017, so I understandably spend quite a lot of time going into… perhaps too much detail. However, I wonder if code is somehow included, since the post doesn’t seem that long. The shortest post is essentially just an advert for an article I wrote for my employer, hence the impressively low 62 words.\n\nOverall I’m pretty happy with an average of ~1k words per post. I’ve always intended to write detailed, unique articles, and this shows they’re usually “meaty” enough to justify publication. Nice! 150k words over 5.5 years is also not too bad, eventually I’d love to do an analysis over time.\n\nOh, and these stats exclude… most of this post, as they were calculated during the writing process!\n\nPersonal site\n\n\n  Total site words: 72107 (average 1716 per post)\n  Total site characters: 613702 (average 14611 per post)\n  Longest post: Reviewing ALL 83 Steam games from the Yogscast’s Jingle Jam charity bundle (part 1 of 3) (6700 words)\n  Shortest post: How to replace a faulty Flexispot standing desk leg motor (348 words)\n\n\nOkay, 6.7k words on a single post is clearly too many, especially as it is just 1 of 3 parts! The Jingle Jam write-up was an incredibly time-consuming project, but I didn’t realise quite how detailed my reviews were until now. Terrifying.\n\nThe short Flexispot article is primarily photos with descriptive text, so no concerns over post quality from me. I’m pretty happy with 72k total words, considering I only started my personal site in February 2022. The average length being significantly longer than my programming site is interesting, I suspect this is due to lots of very long game review / spreadsheet explanation posts, whereas my programming blog has quite a few text-light but code-heavy articles.\n\nInternet history site\n\n\n  Total site words: 5776 (average 1444 per post)\n  Total site characters: 49704 (average 12426 per post)\n  Longest post: 17 years ago today, the Million Dollar Homepage was completed, making a student $1m in 5 months (2373 words)\n  Shortest post: 20 years ago today, the ‘Most Annoying Webpage’ was launched, trapping victims in popups for a few minutes (1392 words)\n\n\nI probably could have worked this out manually, there’s only 3 posts! They’re not as long as I was expecting, especially since these posts usually take multiple days to research. I guess their research per paragraph ratio is far higher, but this isn’t reflected in a simple word count! Similarly, the tens of references in each post aren’t included in the word count.\n\nTotals\n\nAdding up word counts across the 3 sites, we end with 230,126 (152243+72107+5776). 230k words feels like quite a lot, especially as 2 of the sites are under 18 months old, with likely around 90-100k words written in that time period. Apparently 90k words is typical for a novel, so I hope you’ve all enjoyed reading the rather chaotic and varied story over that time period!\n\nConclusion\n\nBefore any calculations, I predicted “my total word count must be in the hundreds of thousands”… and 230k fits within that very broad range. Whilst the totals themselves are relatively impressive, in the future I might improve the plugin to add a breakdown by year, since I strongly suspect mine will ramp up drastically.\n\nSpeaking of the plugin, it’s entirely possible better ones exist. However, a search for “jekyll count words” (and a lot of similar terms) generally showed either the word count in a post (which is included already…), or random chaotic scripts. Matt’s script, whilst simple, was a very understandable “loop through posts, build up stats” style plugin, more of a script than a fully fledged plugin.\n\nThis simplicity meant I could technically write my first ever Ruby code, since his framework could easily have new keywords, logic, or even entire tags added to it. I’m very grateful to his great start, and very impressed that it’s almost all 9 years old with only 1-2 merged PRs since then! Hopefully he’ll agree with my changes to the project, but if not this article should serve as a useful enough guide for others.\n\nBenefiting from then contributing to an open source library is always a good feeling!\n\nEdit: The original plugin author merged my PR only a few hours later, perfect! Have updated wording within the post.\n"
    } ,
  
    {
      "tags"     : "GitHub Actions, Automation",
      "title"    : "How to automatically display your latest posts (from multiple RSS feeds) on your GitHub profile",
      "excerpt"  : "GitHub profile READMEs are a relatively new addition (2020), letting devs add a little description of themselves, and even display dynamic content like latest blog posts or current Spotify track. Whilst I’ve had a basic README for over a year, I recently added a combined list of recent articles from all my sites using a GitHub Action.\n",
      "url"      : "/showing-latest-posts-from-multiple-sources-on-github-profile/",
      "date"     : "Jul 24, 2023",
      "content"  : "GitHub profile READMEs are a relatively new addition (2020), letting devs add a little description of themselves, and even display dynamic content like latest blog posts or current Spotify track. Whilst I’ve had a basic README for over a year, I recently added a combined list of recent articles from all my sites using a GitHub Action.\n\nWhilst there are quite a few GitHub Actions available to display an RSS feed, most of them don’t support multiple sources. I found a few ways to solve the problem by writing my own RSS poller and parsing the data myself, but I wanted something much easier!\n\nLuckily, I found Sarisia’s actions-readme-feed, and used it to create my profile. Here’s how to use it:\n\nCreating a profile repository\n\nBefore we add any complex content, you need to create a profile repository.\n\nGitHub has a detailed guide, essentially:\n\n  Create a public repository with the same name as your username.\n  Create a README.md file inside.\n  Done!\n\n\nPreparing repository\n\nFirst, add placeholder tags inside your README.md to be replaced by the dynamic content. This can be any text, but the default is good enough:\n\n&lt;!-- feed start --&gt;\n&lt;!-- feed end --&gt;\n\n\nNext, inside your profile repository, add a new file at .github/workflows/blog-post-workflow.yml. If adding this via GitHub’s web interface, just type / when creating a new file to also create the directories:\n\n\n\nFinally, you’ll also need to give the GitHub action the ability to commit code, so that it can actually update! This is done in the repository’s settings, under Actions, General, Workflow permissions:\n\n\n\nAdding automation\n\nNow the actual GitHub Action that lives in blog-post-workflow.yml needs to be written! The action’s repository has detailed instructions, here’s my config:\n\nname: All recent posts\non:\n  schedule:\n    - cron: '0 */6 * * *'\n  workflow_dispatch:\n\njobs:\n  readme:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v3\n      - uses: sarisia/actions-readme-feed@v1\n        id: feed\n        with:\n          file: 'README.md'\n          format: '- ${day} ${monthlong} - [${title}](${url})'\n          timezone: 'Europe/London'\n          url: |\n            https://jakelee.co.uk/feed.xml\n            https://blog.jakelee.co.uk/feed.xml\n            https://history.jakelee.co.uk/feed.xml\n            https://minima.jakelee.co.uk/feed.xml\n      - if: ${{ steps.feed.outputs.changed == true }}\n        uses: sarisia/actions-commit@master\n\n\nAnd the output:\n\n\n\nCustomisation\n\nThis config works perfectly for me!\n\nHowever, you’ll undoubtedly want to make some changes, so here are the parts to change:\n\n  schedule:cron: Sets this action to run every 6 hours. I recommend using a cron helper if you want a different time.\n  workflow_dispatch: Allows this action to be run manually, great for testing.\n  format: Defines a slightly different format for each post, as per docs.\n  timezone: Defines the time zone the dates will be formatted in, the “TZ identifier” here.\n  url: Defines a list of RSS URLs to pull from, in this case all my sites.\n\n\nNotes\n\nPerformance\n\nWhilst the time taken to retrieve the RSS feed obviously depends on your site, as mine are cached heavily the GitHub Action is very, very fast! It takes ~7 seconds total, with around half of that setting up the job and checking out the repository:\n\n\n\nGiven this, it’s relatively safe to add more complex logic into the GitHub Action without worrying about using up too much server time.\n\nPotential improvements\n\nThe actions-readme-feed action we’re using for this is good for the basics, but I’d love to see a couple of things added to it. It’s open source so it might be a good opportunity for me to improve my TypeScript skills… eventually.\n\n\n  A way to indicate where articles come from when there are multiple sources (e.g. Jun 24: [Programming] My article about code).\n  An option to only show the first X characters / words of a post.\n  The ability to pull a thumbnail for each post.\n  The ability to “prettify” dates, e.g. “24th June” instead of “24 June”.\n  The ability to set the user-agent for the polling, so that it can be distinguished in server logs from other robots (e.g. for whitelisting).\n\n\nConclusion\n\nSo, my profile now has recent posts showing, nice! It would probably look a bit nicer if my titles were shorter, but old habits die hard.\n\nShortly after originally posting this article, I realised all my displayed dates were a day earlier! This was caused by not setting a timezone and the default being UTC, gotta love dates and times right?\n\nI’m still unsure what I actually want my GitHub profile to look like. A short personal description and these recent posts is good enough for now, but one day I’d love to have an actually aesthetic profile. Perhaps a banner with nice typography, along with some very subtle automatic statistics around commits, languages used, activity elsewhere online, etc.\n\nHowever, it’s very easy to take this too far. There is a showcase site of GitHub profiles, and some of them… are an absolute mess. Personally, I feel the README.md has to be as short as possible, to make the more useful content (recent activity, pinned repos) easier to access. The only exception to this is the intentionally ridiculous ones, like playable Chess or playable tic-tac-toe (with no automation!).\n\n"
    } ,
  
    {
      "tags"     : "Slack, Emojis, Remote",
      "title"    : "Using custom Slack emojis (& reactions) to help define a team identity, encourage engagement, and shape culture 🎉",
      "excerpt"  : "Emojis are fun. As weird as it sounds, custom emoji reactions are one of the main reasons I find Slack and Discord so comfortable to use in comparison to things like Microsoft Teams 😌! So, what makes custom emojis such a useful, even essential feature in a chat platform?\n",
      "url"      : "/custom-slack-emojis-impact-on-team/",
      "date"     : "Jun 27, 2023",
      "content"  : "Emojis are fun. As weird as it sounds, custom emoji reactions are one of the main reasons I find Slack and Discord so comfortable to use in comparison to things like Microsoft Teams 😌! So, what makes custom emojis such a useful, even essential feature in a chat platform?\n\nWhy do emojis matter?\n\nI love emoji reactions way too much 🥰, to the extent that a company’s choice of chat platform actually influences my willingness to join. Hopefully this article can provide some justification for this perspective!\n\nTeam identity\n\nWhen working closely with others for long periods of time, you naturally form some concept of “us”, or “the team”. Having emojis based on this team that can be used in day to day situations helps reinforce this identity, no matter how basic they are.\n\nFor example, on a quiet day I added a varied set of Android emojis to my employer’s Slack. Whilst these are usable by anyone, realistically they are mostly used by Android developers, or those working closely with the Android app.\n\n\n\nAfter I’d used them 1-2x to get the word out, I started seeing them pop up on anything Android related! There’s something oddly heartwarming about seeing your team’s little “Android with sunglasses” icon being used by hundreds of people on app-related company announcements etc.\n\nInclusiveness via inside jokes\n\nWorking in tech, there’s often a system that is unreliable or problematic for various reasons. This might be a third party system, a legacy system, or just one that is performing a tricky task. When the point of failure is recurring, having a “fun” emoji to defuse the frustration somewhat genuinely helps!\n\nThis might be sarcastic (e.g. a system that often appears to be the cause, but is often just a symptom), or genuine (e.g. blame-user). Either way, having an emoji that lets technical &amp; non-technical people allude to this without resurrecting a “X is unreliable” discussion every time can ease frustration.\n\n\n\nUsing individuals is generally not advised (see riskiness of faces), but otherwise the mixture of sarcastic and genuine sentiment lets anything be safely blamed!\n\nLow friction engagement\n\nAs a team grows beyond single digits, it’s just not possible for 20 people to all reply to messages. Emojis, especially custom additions, let anyone agree with a sentiment very quickly without having to overthink their wording.\n\nFor example, on two new engineers’ first day I announced them in our team chat. Without emojis it would have had very few reactions, since there’s not much to realistically comment on, but a collective 🎉 &amp; 👋 is a nice hello for the new joiners!\n\nYou might also notice the seemingly inexplicable pig reaction… This will make more sense after reading microcomedy opportunity &amp; passively shaping culture, but essentially it’s a pun on the new starters being “guinea pigs” (testers) for a new onboarding guide I’d created (more info):\n\n\n\nAs another example, when an Android colleague was leaving the Android “heart” emoji was a cute addition to the standard ❤️:\n\n\n\nThis part is also crucial when a team includes quite reserved or private individuals. Whilst they may not want to send a reply to a message in a large channel, they’re probably willing to do a single click to add an existing reaction! Whilst this is a microengagement, in my opinion it’s significantly better than zero engagement.\n\nMicrocomedy opportunity\n\nOkay, admittedly this one is definitely only applicable to some people, but personally I can’t resist the opportunity to make a bad pun. Reactions let you do that without disrupting conversation, with decoding the joke being a bonus side-quest!\n\nIn the following example, certain processes go through a “Change Approval Board”, AKA CAB. When a reminder about this was posted, obviously the only appropriate reaction was a taxicab emoji… 🙄\n\n\n\nOh, and of course reactions are also great for recognising text-based comedy!\n\n\n\nPassively shape culture\n\nIf your team has appealing emojis, they will be used.\n\nThe company “Moonpig” has a cute pig as their mascot. Since we previously shared a Slack space with them, we still have all their emojis, and they still get used pretty regularly due to being high quality animations.\n\nWhilst creating quality branded animations is perhaps only worth doing in a designer’s spare time, having employees wanting to use the company mascot helps reinforce this branding internally. This will inevitably feed into the company’s interactions with the public, and when going “all-in” enough on your mascot to make it part of your company name, why not set it up for success?\n\n\n\nIf your company doesn’t have a mascot that needs representing, emojis can still absolutely be used to influence overall culture. For example, we currently have the most common reactions immortalised in ultra basic and readable emojis. These can then be used as reactions either in private messages (saving a bit of time / brainpower thinking of a text reply), or in a group chat (letting multiple people say the same thing easily).\n\n\n\nThe reason this is so important is due to the passive nature of the influence. Adding the emojis and using them a few times doesn’t require a meeting or any documentation, appealing ones will naturally spread widely. For example, I added an upbeat “bouncing sun” to use during some hot weather, and before long it was regularly used for anything summer related!\n\n\n\n\n\nCommunication subtlety\n\nUsing emojis as reactions allows a new dimension of communication besides plain text. This could be asking general questions (e.g. “👍/👎” or “🍕/🍜/🥪”), or even judging team sentiment. Whilst this applies to all emoji reactions in general, it applies especially to custom emojis.\n\n\n\nAdditionally, in a direct message reactions let a past message be reacted to without disrupting the current topic. This is useful when something doesn’t justify a thread, but a quick 🙄 or 😂 shows it has been acknowledged!\n\nContaining distraction\n\nEveryone gets bored at work. Personally I find one way to avoid this happening too often is to bring a bit of “myself” into work, through casual chats about non-work things, as a reminder than colleagues are real people not just their job title! Custom emojis help this by allowing a bit of personality to come through, via which emojis choose to use. After a while you might even be able to reliably predict who used which emoji.\n\nInstead of looking at my phone or opening up Twitter, making a dumb bit of microcomedy scratches that “distraction” itch whilst still (just about) providing benefits to the company and colleagues.\n\nWhat are the drawbacks?\n\nRiskiness of faces\n\nDon’t use people’s faces as emojis. It can make someone feel pretty uncomfortable, and there’s no way to “undo” it besides asking the original creator to remove the emoji.\n\nIt’s just not worth it, even for a sarcastic “blame-x” emoji!\n\nMisunderstandings\n\nA picture tells a thousand words, and even an emoji can imply quite a few. Be careful using emojis that have some sort of cultural / meme definition, since to an outsider they might have a very different meaning!\n\nExamples of emojis that should probably be avoided are short-lived / obscure memes like the coffin dance, or internet-specific memes like “bruh”. Use your judgement, if your company has employees in multiple countries across multiple generations, most of your references won’t land! Emoji communication needs the same common sense that applies to text communication.\n\nLuckily I can’t remember a specific instance of an emoji misunderstanding causing an actual issue, but there’s definitely been times when a piece of information has not been understood fully by all readers due to emoji usage.\n\nClutter\n\n300 emojis might be too many. 3000 definitely is.\n\nWhen a Slack instance has been around for quite a few years, especially with all employees (1000+) able to add emojis, the number of custom emojis will become absurd! In this instance, the problem was multiplied by merging two Slack instances and all their emojis (see name conflicts).\n\n\n\nUnfortunately it can be much harder to “purge” no longer needed or duplicated emojis, if only because employees can usually only add new emojis, not delete other people’s.\n\nWhilst each addition or group of additions are probably fine (e.g. adding the letters A-Z in a “fun” font for making an announcement’s title more attractive, or some cute blob emojis), these add up over time:\n\n\n\nDiving through the clutter can be interesting, with some emojis’ ongoing existence being truly ridiculous!\n\n\n\nQuality control\n\nNot all emojis are created equal. If you use dark mode, you’ll end up seeing a lot of emojis with ugly white borders!\n\n\n\nThere’s not really any way around this, since other people’s emojis can’t be edited. All you can do is ensure your emojis have no background or weird artifacts.\n\nName conflicts\n\nWe recently merged two large, long running Slack instances. Whilst this resulted in a lot of duplicated common emojis with different names, emojis that shared a name got renamed! For example, “no” and “no” became “no” and “no-6759”, presumably some sort of internal ID. Whilst this isn’t too bad (except where the new correctly named emoji was worse than the old one!), it contributed significantly to the massively cluttered emoji base.\n\n\n\nWant to say “Thank you” to a colleague with an emoji? Well, here’s 9 ways to do it! Emojis are meant to condense an idea / response into a single image, if there’s too many choices then the user needs to spend brainpower picking between them again, and we’re almost back where we started. Oops.\n\n\n\nI find this most often happens when a phrase has a lot of variations, each with an emoji set. For example, “ta”, “thanks”, “thankyou”, “tyvm”, and “ty” might be the phrases different people search to find the correct emoji. Emojis can have aliases set, so these are worth setting if a new emoji is intended to be widely used.\n\nFinding Slack emojis\n\nDesigners\n\nThe very best emojis will be hand-created by internal designers, giving a consistent feel across all. This approach (in the context of a company mascot) was discussed in shaping culture, and is definitely to be preferred if there is designer capacity.\n\nEmoji sites\n\nSlack and Discord have pretty loose requirements for emojis, so luckily emojis created for either platform work on both.\n\nThere’s a few different sites for finding emojis, and they weirdly all seem to have different emojis available. I’m not sure how they find them, but they’re all worth searching to find as many options as possible.\n\nIn this example I’ll use the search term “Sun”, as a generic phrase that should yield plenty of results.\n\n\n  Discords.com: ~400 results, with a mixture of GIFs and PNGs. All have “sun” in the name.\n  Slackmojis.com: ~200 results, all quite low quality / small but relevant.\n  Emoji.gg: Hundreds of results, with around half being actually relevant to the search term.\n  Discadia.com: Hundreds of results, with most entirely irrelevant. Basically useless.\n\n\nEmoji support by platform\n\nSlack has by far the most “emoji-friendly” platform, with Discord placing strict limits and (by default) only allowing server moderators to edit emojis. Teams meanwhile has no support for custom emojis besides third party extensions all users need to install.\n\n\n  \n    \n       \n      Emoji support\n      Custom emojis\n      Who can add (default)\n      Max custom emojis\n    \n  \n  \n    \n      Slack\n      ✅\n      ✅\n      Anyone1\n      Unknown, 5k+\n    \n    \n      Discord\n      ✅\n      ✅\n      Admins\n      ~100-300, depends on boosts2\n    \n    \n      Teams\n      ✅\n      ❌3\n      N/A\n      N/A\n    \n  \n\n\nConclusion\n\nEmojis are a completely valid form of communication, improving text messages as much as tone of voice improves conversations. They are instantly accessible to anyone, and so long as used sensibly, can drastically change how relaxed and fun an online workspace feels.\n\nIf you have any input over emojis at your workplace, try adding a few new useful ones, they’ll spread amazingly quickly! A few suggestions:\n\n\n  Basic terms e.g. “yes”, “no”, “added”, “thanks”, “fixed”.\n  Company services / platforms e.g. “Android”, “OurServiceA”.\n  Seasonal / company events e.g. “Christmas”, “Offsite2023”.\n\n\nWhilst most points in this article apply to both standard emojis and custom emojis, there’s an extra “catch” to standard emojis: they aren’t always the same! They often vary significantly across platforms (although they are mostly standardised now), and can even change over time:\n\n\n\nImage from @Emojipedia’s tweet on Oct 14, 2021.\n\nReferences\n\n  \n    \n      https://slack.com/intl/en-gb/slack-tips/upload-custom-slack-emoji-to-express-your-unique-office-culture&amp;title=slack.com &#8617;\n    \n    \n      https://discord.com/blog/beginners-guide-to-custom-emojis &#8617;\n    \n    \n      Note that a custom third party “emojifier” seems to exist for Teams, but it’s very clunky and essentially just runs a constant find &amp; replace for emoji names in the chat. &#8617;\n    \n  \n\n"
    } ,
  
    {
      "tags"     : "Pixel Blacksmith, Android, Project",
      "title"    : "New project: Pixel Blacksmith 2 AKA Purple Blacksmith",
      "excerpt"  : "8-9 years later, it’s time for a sequel to a project I worked on obsessively, which taught me all the basics of Android development and publishing! Pixel Blacksmith’s sequel has finally started development, here’s all the info on the game, and some explanation for why it’s happening now.\n",
      "url"      : "/introducing-pixel-blacksmith-2/",
      "date"     : "Jun 14, 2023",
      "content"  : "8-9 years later, it’s time for a sequel to a project I worked on obsessively, which taught me all the basics of Android development and publishing! Pixel Blacksmith’s sequel has finally started development, here’s all the info on the game, and some explanation for why it’s happening now.\n\nI first got into Android development close to a decade ago, and learned entirely through building my game Pixel Blacksmith in my spare time. Having a project like that really helped provide the motivation &amp; direction for learning, and the fact that it became surprisingly successful (and profitable!) undoubtedly helped my career.\n\nSo, since I’m moving back into Android development (from management) in July, what better time to relearn modern Android than with a sequel?\n\nGame overview\n\nSo what is Pixel Blacksmith 2? Well, it’s a layered idle / incremental game.\n\nThe vision is to end up with multiple layers of cohesive games, with each “layer” having multiple playthrough / automation “paths”.\n\nFor example, the first layer “Machine” is a puzzle-solving layer. Whilst this can be manually completed by solving all the puzzles, it can also be automated via each “path”. Unlocking additional solving options will require a specific manual action, so players will need to balance the ease of automation with the control of manual completion.\n\nThe overall goal will be to defeat, and ultimately control, the “purple”, an all-encompassing alien virus introduced clumsily in Blacksmith Slots.\n\nLayers\n\nThe easiest way to think of the game’s structure is with an overview of all the layer &amp; path combinations:\n\n\n\nEach layer will be a different genre of game, and almost unrecognisable from the layer before. For example one may be solving basic puzzles, one might be strategy, one might be an RPG, etc. I’m tackling the easiest one first…\n\nLayer 1: Machine\n\nThe first horizontal “layer” will be a fully contained game, all about fixing a machine. Whilst I haven’t ironed out the details yet, this will likely be done by solving a multi-level collection of different puzzle types. For example, maybe a few “tap numbers in ascending order”, “predict the coin toss 3x in a row”, or countless others.\n\nAs this is the first playthrough, these puzzles will all have to be solved manually. This might take a while, especially if there are more difficult ones mixed in (e.g. “win a game of solitaire”). So where’s the complexity?\n\nPaths\n\nOnce every puzzle on every part of the machine has been completed, the machine is fixed! However, this is only the “manual” path, the simplest but also most tap-intensive.\n\nAs can be seen in the diagram above, there are likely to be 5 paths that control how a layer can be completed. Unlocking new paths will likely be done via completing feats whilst replaying layers (e.g. “Manually complete Machine in under 10 mins”). In-game, this will be explained as passing on the machine (/ shop / town etc) to your sibling / descendant / another family!\n\nThese paths will relate to each other constantly, and you’ll end up needing to master all of them to progress. Using Machine as an example, here’s the possible completion paths (note that they are very unbalanced currently!):\n\n\n  Tedious: Manually completing every puzzle. Very click intensive and basic.\n  Training: Hiring an assistant. Less click intensive, but takes breaks and is quite slow.\n  Technology: Building a machine to complete the machine. Reliable, predictable, doesn’t require breaks, but high up-front cost.\n  Taming: Training a pet. Similar to Training, but less reliable and cheaper.\n  Turning: Making the purple (the antagonistic alien goo) fix the machine. End-game content, requires mastery of all other paths.\n\n\nUpgrades\n\nUpgrading will play a key part in the progression system. Whilst every layer will have an upgrade tree (for example to reduce the number of puzzles or their difficulty), there will also be upgrades for every possible path. For example the “Manual” path of “Machine” might let you upgrade attributes of every puzzle, or the chance to skip a puzzle step.\n\n\n\nProject goals\n\nSimilar to Pixel Blacksmith 1, this project has a number of goals that luckily align with each other:\n\nLearning\n\nRealistically I’m no longer on the “cutting edge” of Android development. I missed most of Jetpack Compose, I haven’t tried version catalogs, and I’m just generally behind the curve on most developments in the last few years.\n\nBy utilising all of the latest and greatest technology in this project, I can get myself back up to speed. I’ve always found Google’s codelabs and tutorials miss a lot of the “real world” issues that will be encountered, hence the benefits of having an actual project.\n\nTestbed\n\nWhen a new technology is announced, it’s hard to find a use for it without a modern codebase. If you’re working in an outdated codebase, there’s no point paying attention to new libraries since… you won’t be able to use them.\n\nHaving a modern project means new libraries can be tried out, whilst the fact it’s a personal project means unstable APIs can be deployed into production. Google IO etc will suddenly become a lot more relevant!\n\nUsers\n\nI haven’t dealt with “real users” in a while. During Pixel Blacksmith’s peak I was replying to (usually positive!) customer feedback most days, and it was honestly enjoyable. Having real people caring about what I did, minus all the “protections” you get in a larger company was extremely motivating. Fixing a bug became a thing people cared about, not just a ticket on JIRA.\n\nAs my new job is at a startup I’ll likely be a bit closer to our userbase, and having recent experience with the positive &amp; negative pressure this entails can’t hurt.\n\nMoney\n\nRealistically, Pixel Blacksmith never made that much money. However, it would be nice to have a side income, although it’s unlikely to ever pay close to minimum wage for the hours worked!\n\nWriting\n\nI’ve been trying to get into writing fiction, since I’ve always found it so much harder than non-fiction. This will be a good chance to give it a go, whilst also being constrained / guided by the necessities of the game. Translation will be an issue, but that can wait!\n\nTechnology\n\nSo, what technology is Purple Blacksmith going to use? Well, basically just a list of what Google currently recommends!\n\n\n  Language: Kotlin\n  Architecture: Modules, MVVM\n  DI: Hilt\n  UI: Compose\n  Concurrency: Coroutines (Flows)\n  Backend: Firebase\n  Payments: Google Pay\n  Database: Room\n  Version management: Version catalogs\n\n\nYou get the idea! I’d also like to try Kotlin Multiplatform with it eventually, but that’s much, much later.\n\nProgress so far\n\nSince this is my first real new project in a few years, it was a slow start. However, I’ve now got a basic project sorted with all the core Android technologies I want! I also needed to learn Compose, so even just having a navigatable app that can update database values &amp; listen to them elsewhere is a major checkpoint.\n\nThere’s also a lot of work around data structure that has been a bit tricky. For example, how to store the game data of generated puzzles, be able to generate them on demand, load the saved data, etc. All of this is time-consuming, but a solid data structure will make adding a new puzzle or changing game rules significantly easier later on.\n\nAs this is a private project for now, I won’t be sharing day by day updates, but I’ll likely make posts here when major checkpoints are reached. The following screenshot looks pretty dull, but is actually an implementation of generating, storing, and loading a “grid” (multi-dimensional array) of values, ready to be actioned in a puzzle screen.\n\n\n\nThe values at the top are updating automatically, and a levelling mechanism is also implemented. Obviously, there’s a lot left to do before the game is actually useful to anyone!\n\nSome of the problems I solve along the way will end up being their own articles, for example how I end up implementing the complex upgrading system.\n\nPlan\n\nOverall, I’ve got a 7 stage plan for Purple Blacksmith, where I’m currently around halfway through the 2nd stage:\n\n\n  Stage 1: Planning: General prep of project, design, requirements. Completed.\n  Stage 2: Proof of concept: Implementing core mechanisms, puzzle generation, upgrade buying, all desired technologies. In progress.\n  Stage 3: MVP: Get the core gameplay loop working, and have something resembling a real game.\n  Stage 4: Tidying: Code tidying, testing, organising, tidying UI, registering domains etc.\n  Stage 5: Features: The fun bit! Adding cloud saves, notifications, offline progress, payments, all the features that make a game high quality.\n  Stage 6: Alpha: Polish the finished parts, start prepping future work. Add instructions / tutorial.\n  Stage 7: Playtest: Get some testers, see what they think!\n\n\nAnyone who has worked with me before knows I’ll have much more in-depth notes than these, but they’ll do for here! Here’s my currently in progress notes, there’s a lot to do:\n\n\n\nConclusion\n\nSo, what’s the summary of this long, rambling post? Well, that Purple Blacksmith is a thing, it’s very early in development, but it feels really, really good to be passionate about making a game again.\n\nHopefully more updates soon, thanks for reading!\n"
    } ,
  
    {
      "tags"     : "Remote, Onboarding",
      "title"    : "An example of onboarding process & documentation for remote developers joining a specialised team",
      "excerpt"  : "Onboarding engineers to a project is hard. Especially if you’re in a small team (e.g. Android developers) without a whole HR framework, and instead have to make up your own processes! I’ve onboarded tens of engineers (and been onboarded of course), so here’s a few mistakes I’ve learned from, and my current preferred approach for onboarding new engineers.\n",
      "url"      : "/example-onboarding-docs-remote-engineers/",
      "date"     : "Jun 9, 2023",
      "content"  : "Onboarding engineers to a project is hard. Especially if you’re in a small team (e.g. Android developers) without a whole HR framework, and instead have to make up your own processes! I’ve onboarded tens of engineers (and been onboarded of course), so here’s a few mistakes I’ve learned from, and my current preferred approach for onboarding new engineers.\n\nImportantly, I am excluding all company-wide onboarding. For example, GDPR training, financial predictions, all of that is completely out of scope. I’ll only cover the onboarding into an actual software team, not the company itself.\n\nFailed approaches\n\nBefore I get into the approach I went for, there’s been a few previous approaches that didn’t work too well:\n\nNothing structured\n\nAlthough it wasn’t exactly planned… I’ve been on both sides of an essentially non-existent onboarding process. Whilst this isn’t the end of the world for more senior engineers who can hunt most information down themselves, more junior / quieter ones may struggle. A few months of drip-fed learning might transfer as much information as a week of planned onboarding.\n\nThis is probably the worst option possible, but the one most teams will fall into by default. Uh-oh!\n\nToo many meetings\n\nHaving multiple, multi-hour “onboarding” calls / screen shares in the first few days ensured the new joiner was exposed to everything they needed… but did they absorb any of it? Whilst this is undoubtedly better than having no onboarding at all, it has a few risks.\n\nI found new joiners totally understood everything whilst in the calls, but didn’t really retain much of it. A good example of this is technical onboarding: whilst having 1hr of general project architecture followed by 1hr of looking into the actual code is efficient, it’s overwhelming. The key points at the start will be totally lost by the end, regardless of how many notes the new joiner is making.\n\nIt’s also very hard for the new starter to refer back to missed bits and pieces later, besides asking someone to repeat themselves. This is a lot of wasted time and effort on both sides. Finally, new joiners are often focusing quite a bit on making sure their new employer / colleagues like them, so are socialising as much as learning. Not ideal!\n\nToo much documentation\n\nAn alternative approach to this fully synchronous approach of all meetings is fully asynchronous: all documentation.\n\nAll teams struggle with documentation, but almost all have at least a “semi-useful” knowledge base / wiki / notion / confluence / etc. This can be leaned on heavily for onboarding new starters, and will ensure they have access to all information at any time, and can easily refer back to it.\n\nThe trade-off with this approach is essentially the opposite of too many meetings. Whilst the starter will have all the information they could ever need, they won’t know what they need to know. With a flood of hundreds of pages, how can the new starter know what they need?\n\nI typically provided 5-10 “starter” pages for them, but this changed over time, and the documentation of course suffered all the usual issues of being out of date, unmaintained, misleading, etc. Additionally, this approach relies entirely on the joiner being very self-sufficient, finding out for themselves what they need to find out, etc.\n\nPriorities\n\nOkay, so I know what didn’t work. What should my approach have?\n\n\n  Primarily (but not entirely) asynchronous: The joiner should be able to refer to information whenever they need to, but also be guided through a “narrative” of the app, and advised where to look.\n  Always up to date information: The documentation should be useful for everyone, not just the new joiner. This way it’s in everyone’s best interests to maintain it.\n  Guided, with flexibility: The new starter should never feel lost, but should have the freedom to dive deeper into areas that interest them.\n\n\nDay by day\n\nThe onboarding should be guided, with a clear set of goals and information for each of the first few days. The engineering manager should always be available to answer any questions and schedule any 121 sessions, but won’t be needed every hour of every day.\n\nInformation like team members, office information, company systems are split into a day-by-day basis, and this is the main source for this information. As such, these pages are useful to (and maintained by) all existing employees too!\n\nI used Notion for this, the platform doesn’t matter. I highly recommend giving Docs for Developers a read beforehand if possible, to make sure the knowledge is shared as effectively as possible.\n\nDay 1: Product &amp; Team\n\nThe first day isn’t at all technical, it’s all about the product itself and the team. As such, the goals are:\n\n\n  Have access to all required systems (e.g. Slack, Email, JIRA)\n  Know where &amp; when to talk to people (e.g. team Slack channels, agile ceremonies)\n  Have introductory sessions with Product &amp; Design representatives.\n\n\nWhilst this may seem like almost nothing on a first day, that’s by design! If the new joiner has capacity they can dive deeper into areas they want to get ahead on, or even just socialise more. There’s a million new things to learn, there’s no need to front-load all the information.\n\nThe introductory sessions should be organised by the hiring manager (who should be doing mini-checkins throughout), and will be covered in product and design. For asynchronous information, here’s the documentation included in Day 1:\n\nTeam\n\nEveryone in the team, where they are, what they do, any other relevant information.\n\nEmojis are great for making this a bit more friendly and compact, although be careful how many people you count as part of “the team”. We’re close to 20, and that’s definitely a limit. For ours, I tried to use horizontal space to represent different “sub-teams”, and vertical space to represent different “specialisms”:\n\n\n\nOf course, this would be much tidier if everyone had similar length names, and I could figure out a clear emoji for “Product Design” or “Backend”! Linking to any official org chart also lets people “double check” the company’s structure, whilst also finding out who manages the managers etc.\n\nLocations\n\nDepending on how in-person your team is, office information might be essential. This doesn’t need to be a detailed history of the company offices etc, but each of our 3 locations have a page containing essential information:\n\n\n  Floor plan: People forget where meeting rooms / bathrooms are!\n  Facilities: If there is a gym, bike rack, shower, document them.\n  Meeting rooms: How can a meeting room be booked? Where are they located?\n  Building-specific info: If there’s a smoke alarm test every other Monday, document it. If there’s an entry door code, document it.\n\n\nSystems\n\nAs mentioned, the new starter likely needs access to a surprising amount of company &amp; team specific systems. Whilst many of these will be controlled by Single Sign On or other in-house systems, they still likely need documentation on how they work.\n\nEven though most people will have experience with common systems like Firebase and JIRA, there will be specific quirks that should be documented. This might be how to gain access, how to workaround a bug, etc. Note that this documentation can (and should) be reused whenever non-team members also need basic training in a system.\n\nThe new starter probably won’t need these systems initially, but they should know what they are, what they do, and where they are.\n\nCommunication channels\n\nFinally, they also need to know the formal and informal discussion areas. Teams often have a subteam channel, a speciality channel, a formal discussion channel, a casual discussion channel, and many, many more. New starters will often need 100+ channels, so a brief description &amp; categorisation of these will help the newcomer know what can be safely muted!\n\n\n\nDay 2: Engineering\n\nDay 2 is more of a traditional “onboarding” session, with a focus on technical knowledge sharing.\n\nThe goals are:\n\n\n  Have access to all necessary codebases.\n  Understand the basic parts of the product.\n  Have a local development environment setup, and can deploy the service / app / website locally.\n\n\nI’d usually define Goal #1 as being in the organisation’s GitHub team, and can pull &amp; push to all projects that need to be worked on. Codebase access will of course vary between organisations, and may take multiple days depending on security / IT.\n\nFor Goal #2, most of this will be done by a meeting with a senior or principal. Finally, Goal #3 may need descoping if a full local deployment isn’t realistic, as deploying locally can be a 5 minute or 5 hour job.\n\nDay 3: Everything else\n\nThe final onboarding day is a bit of a “catch-all” for everything missed so far. The goal for this final day is nice and simple:\n\n\n  New starter understands everything so far, and is ready to pick up their first (small!) ticket!\n\n\nFurther reading\n\nA list of additional pages to read can help eager new joiners get ahead of the game, whilst also providing a clear list of “great” pages. For us, this was things like how to handle bugs, the app roadmap, how to handle queries from other teams, etc.\n\nProcesses\n\nWhilst most companies use some form of agile, the new starter will likely need to be shown how the team handles things specifically. Ideally this will also be documented somewhere, but a session with an engineering manager (or agile coach / scrummaster) might help. Additionally, PR and release processes will need sharing.\n\nWider company\n\nOften forgotten, the new starter probably needs to know people outside the current team!\n\nFor example, there will likely be teams that work closely with your team, your counterparts in sister companies, as well as of course all the senior management figures. It’s good to know where the “chain of management” goes, from the new starter all the way up to the CEO.\n\n\n\nMisc notes\n\nFinally, there’s a lot of information that’s just good to know. This might be finishing early during summer, the history of the team / product, or anything else. As this is the “everything else” of the “everything else”, it’s very flexible.\n\nOnboarding sessions\n\nWhilst most of the information will be asynchronous, actual handovers of information are still absolutely crucial. The specific make-up varies by company, but for us the three main entities during development are Product (e.g. Product Manager), Design (e.g. App UI Designer), and Engineering (e.g. Principal Android Engineer). All 3 of these key individuals have a unique perspective, and the combination of them should ensure the new starter gets a great overview.\n\nProduct session\n\nA product manager often has the most complete view of the product, understandably so. This session should cover what the product does (e.g. Mission), where it currently is, and where it’s planning to go (e.g. Vision / Roadmap). Possible outcomes could be:\n\n\n  New starter has in-depth understanding of the product, and understands the vision behind it.\n  New starter knows what the company’s major upcoming features are, and how their team fits in.\n  New starter understands how these features are planned, prioritised, and worked on.\n\n\nEngineering session\n\nThis will likely be a typical onboarding to the codebase, software development practices, and overall approach. The basic outcomes of this could be:\n\n\n  New starter knows the overall vision of the codebase.\n  New starter understands the coding conventions followed.\n  New starter is confident they can navigate the codebase themselves.\n\n\nDesign session\n\nWhilst product and engineering may seem to be a complete picture, there’s often a role / individual in a team that has an outsized impact, and ends up representing the customer to some degree. In your company this might be a customer support representative, a quality engineer, or perhaps also a designer.\n\nThis session should show the product from a customer perspective, to help the new starter understand what the product is capable of, and why it feels and behaves the way it does. If this role is filled by design in your team, it will necessarily be a more visual session.\n\nPossible outcomes could be:\n\n\n  New starter knows all screens / areas of the product, and the current user flow.\n  New starter understands how the design team works, and the tools they use for wireframing, prototyping, reviewing work etc.\n  New starter can work effectively with design, knows how / when engineers are involved in feedback, how to raise design concerns, etc.\n\n\nImprovements to make\n\nOf course, this approach isn’t perfect. No approach is! However, it seems a bit better than the previous attempts, and hopefully it’s made new engineers have an easier transition into our team.\n\nIt’s crucial to factor in non-team onboarding throughout this process. If your company already has a structured onboarding for the first few days, it may not be worth starting your onboarding until a few days later. Contrastingly, if there is no wider onboarding (for payroll, customer support, everything else) you may need more than 3 days.\n\nWhilst I’ve extolled the virtues of giving the new starter flexibility in when they learn new information, I think ideally the onboarding process would be slightly more structured. It’s often a challenge to fit the onboarding sessions around busy calendars, and it’s important the new starter doesn’t feel like they are a burden to existing employees.\n\nConclusion\n\nOverall, I’m really happy with the day-by-day approach, and the flexibility it gives both the onboarder and the onboardee. However, itt’s definitely a tricky balance providing too much vs not enough information, and it needs personalising to the specific company, team, and even individual joining.\n\nFor example, I personally massively prefer reading information and being able to refer back to it, to the extent that things told to me in meetings are essentially forgotten unless I make notes! As such, this approach would suit me perfectly, as I could easily “read ahead” of the next day, remind myself who key individuals are, etc. However, for someone who prefers more conversations and discussions, it might be helpful to be “walked through” some of the information on a call. Catering the onboarding to the individual is a good way to ensure it all actually sinks in.\n\nIf you’ve tried the day-by-day onboarding style let me know how it went, otherwise I’m very interested in alternative approaches that might work better!\n"
    } ,
  
    {
      "tags"     : "Project, Domains",
      "title"    : "Introducing \"diet.co.ke\", a silly mini-project",
      "excerpt"  : "This weekend I discovered Kenya sells “co.ke” domains. Obviously the only thing to do was register “diet.co.ke”, and put up a fun little landing page!\n",
      "url"      : "/diet-coke-miniproject/",
      "date"     : "Jun 4, 2023",
      "content"  : "This weekend I discovered Kenya sells “co.ke” domains. Obviously the only thing to do was register “diet.co.ke”, and put up a fun little landing page!\n\ndiet.co.ke\n\ndiet.co.ke’s code is open source, and someone has already submitted a PR fixing a few UI bugs. I’m not intending to make it anything more than the current little animation, short and sweet:\n\n\n\nWarnings\n\nFor anyone else starting a similar project, a few warnings:\n\nBuy directly\n\nMost registrars will charge unreasonable amounts for a .co.ke domain. For example, OnlyDomains charges $35 to purchase, and $70 to renew. 101Domain charges $58 to purchase, and $72 to renew. So, it must be an expensive domain to buy right?\n\nNope. It’s 1200 Kenyan shillings from a Kenyan registrar, this is around $9. After taxes etc the domain cost me $11, I have no idea how registrars can justify charging 5x the actual cost!\n\nKenyan registrar\n\nThe .co.ke registrar (at least, the “webhost kenya” one I found) is… not perfect. It took 18 hours after paying for the domain to actually gain access to it, and nameservers / DNS changes have been extremely slow. I’m still waiting for some final propagations 48 hours later, although that isn’t entirely the registrar’s fault!\n\nUpdating nameservers and other changes were a little confusing, with things like success messages showing where they shouldn’t:\n\n\n\nWhilst writing this article the management site also appears to have gone down completely for a bit, not what you want from the place that controls your domain:\n\n\n\nCloudflare\n\nCloudflare don’t support .co.ke domain registrations. You can still use Cloudflare, but the domain can’t be transferred to them:\n\n\n\nConclusion\n\nNo real conclusion, except I hope you like diet.co.ke!\n"
    } ,
  
    {
      "tags"     : "GitHub Pages, Jekyll, HTTPS",
      "title"    : "How to fix an incorrectly HTTP canonical URL / resource when serving Jekyll over GitHub Pages with HTTPS",
      "excerpt"  : "Recently I was looking at this site on Google Search Console, and noticed a few warnings about HTTP canonical URLs. This was a little confusing, since all my content is HTTPS, and it was only happening on one site. Turns out the problem was a GitHub Pages setting I’d forgotten to change…\n",
      "url"      : "/jekyll-github-pages-https/",
      "date"     : "Apr 30, 2023",
      "content"  : "Recently I was looking at this site on Google Search Console, and noticed a few warnings about HTTP canonical URLs. This was a little confusing, since all my content is HTTPS, and it was only happening on one site. Turns out the problem was a GitHub Pages setting I’d forgotten to change…\n\nThe issue\n\nSo, here’s the warning I had in Google Search Console:\n\n\n  HTTP marked with canonical tag\n\n  These pages are not served over HTTPS. HTTPS is a requirement for a good page experience.\n\n\n\n\nLooking at this site’s source code… Google had a good point! All internal references were to http URLs that were then being redirected to https via Cloudflare when navigated to. This applied to asset references as well as the canonical URL.\n\n\n\nThe investigation\n\nI’m in a unique situation where I have multiple almost identical sites, helping narrow down the problem. Since this issue only affected my programming site, I knew it wasn’t a template issue, and was specific to this project.\n\nSince the issue is in the source code, I assumed it had to be within my codebase. As such, I looked into where this base URL comes from, including a completely unnecessary dive into the Jekyll SEO plugin that generates these meta tags.\n\nAfter looking into the SEO plugin, my theme (minimaJake), and this site’s config and finding no issues at all, I widened my search to GitHub pages. Sure enough, it was an obvious fix…\n\nThe solution\n\nTick this box:\n\n\n\nYep, that was it. Ticking that box and rerunning the GitHub Actions build now generated HTTPS URLs in the source code, and solved the issue entirely.\n\nInitially, I didn’t understand how this fixed it whatsoever. Surely this checkbox only changes how the already generated website is served, and doesn’t do anything about rewriting code?\n\nNope! I compared the code generated by the GitHub action with the checkbox checked and unchecked, and every meta URL changed between https:// and http://. This means the “Enforce HTTPS” GitHub pages checkbox impacts the default Jekyll GitHub action!\n\nI suspect this fix also applies to many other Jekyll unsecured HTTP issues, since it’s not very intuitive that the GitHub action (usually controlled via a static config file) changes behaviour based on a GitHub setting.\n"
    } ,
  
    {
      "tags"     : "WFH, Flexispot, Technology",
      "title"    : "Setting up a tidy 3-monitor, 2-laptop standing desk workspace",
      "excerpt"  : "Exactly 2 years ago, I wrote about my revamped WFH setup. Now I’ve moved… everything has changed again! Here’s everything wrong with my old setup, and how I built the new one. As before, this is partially to remember my own reasoning, and partially to provide ideas for anyone with similar needs.\n",
      "url"      : "/improving-my-triple-monitor-dual-laptop-standing-desk/",
      "date"     : "Apr 22, 2023",
      "content"  : "Exactly 2 years ago, I wrote about my revamped WFH setup. Now I’ve moved… everything has changed again! Here’s everything wrong with my old setup, and how I built the new one. As before, this is partially to remember my own reasoning, and partially to provide ideas for anyone with similar needs.\n\nRequirements\n\nAs a reminder from the last post, I have a weird working setup where I use a (personal) Windows machine and (work) Macbook all day. I also need to frequently be on video calls.\n\nBefore\n\nFirst up, here’s my old setup which was… okay:\n\n\n  \n    \n      Overview\n      From above\n      Under\n    \n  \n  \n    \n      \n      \n      \n    \n  \n\n\nAfter\n\nAnd here’s the new one:\n\n\n  \n    \n      Overview\n      Standing\n      Sitting\n    \n  \n  \n    \n      \n      \n      \n    \n  \n\n\nChanges\n\nOkay so yes, pretty much everything has changed except monitors &amp; peripherals!\n\nEnvironment\n\nYes, I’ve moved! I’m now in a dedicated office with lots more space, shelves where I want them, soft carpets, etc. I’ll do a full room tour eventually, but for now the main improvements are:\n\n\n  Decor: Comfy carpet underfoot and my favourite colour on the walls, much nicer than hard floorboards and plain white.\n  View: A large window looking out over my new garden, where my cat Cassie is often hunting leaves or similarly dangerous prey. There’s also a blind colour-matched to the wall (Breton Blue).\n  Lighting: This large window also means I have natural light on my face, with the option of additional soft lighting from a lamp. There’s also a Philips Hue main light. Much better than the monitor-lit face before, now I have more options than washed out / in darkness.\n  Creativity: Having more space means I can have a basic whiteboard up on the wall for notes / UI sketching, and my old desk can become a big space for… something.\n\n\nChair\n\nNice and simple, I moved from a basic cheap office chair to IKEA’s Markus chair. It’s comfier, has a headrest, and is perfectly weighted so I can lean back whilst sitting on my legs and it becomes a little nest whilst gaming!\n\nFrom PC to Laptop\n\nSince moving out of a small 1-bed apartment into a house with plenty of places to work, I was spending almost none of my free time in my office. In fact, I was using my work laptop just to watch Netflix or reply to emails in other rooms.\n\nIn addition to a lack of flexibility, my mid-range “gaming” PC was a few years old so performed worse than a 4 year old macbook for everything except gaming! Considering that I only play a few hours a week and don’t care much about graphics, it seemed time to purchase my first ever personal laptop. Finally, I was also concerned about the risk of any power outages causing damage to my PC / turning it off. With a laptop there’s hours of battery life left.\n\nAfter plenty of research (asking Reddit, then Googling lots of dumb questions before coming to the same conclusion…), I bought the Lenovo Thinkbook 16p. The vendor I used was selling their last few models at a crazy discount, so I got a new £1.3k machine for under £900! I still haven’t seen another deal under £1k, and it has everything I need:\n\n  16” screen, so it’s portable but doesn’t feel cramped.\n  Air intake on the bottom, so I can mount it under the desk.\n  Great CPU (AMD Ryzen 9 5900HX), a staggering 6x better than my old CPU..!\n  Great GPU (RTX 3060 Laptop), around 30% less powerful than my old GPU, but enough for 60 fps on Forza Horizon 5 on high.\n  Good battery life.\n  A very detailed review mostly highlighted flaws I don’t mind (poor webcam, few ports, etc).\n\n\nThe stereotype of a relatively powerful laptop that can also run games is an angular, LED-covered bulky monster, with deafeningly loud fans. There’s always one student in a university lecture who deeply regrets their noisy Alienware laptop! Luckily the Thinkbook 16p has:\n\n  No fans when under light load.\n  A professional, “normal” design. It wouldn’t look out of place in a lecture or an office.\n  No LEDs (although there is a backlit keyboard that has to be disabled).\n\n\nA full explanation is in Monitors, however this is the cabling setup that the new laptop enabled:\n\n\n  \n    \n      Old\n      New\n    \n    \n      \n      \n    \n  \n\n\nDesk &amp; power\n\nYep, that’s a standing desk. I’ve wanted one for a while, and moving seemed like the time to make the change over to a Flexispot E7 (with 140x80cm black walnut top). I’ve also got Flexispot’s cable tray to bring some sanity to my cables.\n\nSo far I’ve found it’s made me much more focussed in meetings, especially those just after lunch or in the mornings. I tend to use it for 2-3 hours total per day, and it convinced my partner to get a matching one too!\n\nI briefly tried using a standing desk before getting my laptop but… it looked ridiculous (see bonus images). I also originally had a smaller desk, but the laptop mounting wasn’t possible, and my monitors looked too large. Note that the control panel has been mounted on the left to allow mounting the laptops, and to avoid accidental activation.\n\nTo allow the desk height to change whilst also keeping cables managed, I realised I had to basically hide the mess under the desktop. So, everything is plugged into 2 extension cables screwed into the underside, and only their cables have to move when the desk does. Images of this are in bonus images. The left extension cord handles the 3 monitors &amp; desk, whilst the right one handles both laptops. I’m a little paranoid about electricity, so pulling half the total power from each side of the room makes me feel a little safer. The cable of these extension cords are attached at the bottom to hide them behind the legs.\n\nDesk clutter\n\nDespite still having plenty of desk space, I also removed some of the unnecessary bits and pieces. My controller is put away, as it doesn’t need to be constantly accessible. Same with my phone, although I might add the wireless charger back again soon.\n\nAlso, since I love my new desk, I’m protecting it a bit with a mousemat and coasters for drinks.\n\nLaptop mounting\n\nMy personal laptop is on the left, my work laptop on the right. Both of them have air intakes on the bottom, and have been configured to not enter sleep mode when their lid is closed unless they are inactive for a long period (or are on battery).\n\nAs the 2 monitors are USB-C, they can be swapped between the two machines. My personal laptop has power input on the back, then the two USB-C ports on the right. My work laptop has 2 USB-C ports on the left, then a hub on the right with power, a HDMI monitor, and my webcam. Since my work laptop rarely leaves this dock, it’s fine to have a more complex dock.\n\nTo actually attach the laptops, I wanted white brackets with approximately 1” space for the laptop. Weirdly, all the under-desk laptop mounts I could find either weren’t white, looked weak, or were unnecessarily big. Eventually I found these mounts for blinds, which perfectly met my requirements. They’re made of sturdy metal, are pretty cheap, and can be mounted wherever makes sense for your laptop. Perfect!\n\nMonitors\n\nWith the old setup, 2 of my monitors had 2 cables coming out of them, one to each machine. This plus power cables meant… a lot of cable management. With the new setup, each of the multi-machine monitors only has 1 DisplayPort -&gt; USB C cable that can then be swapped between machines.\n\nThis avoids the issue of my mouse sometimes going to an invisible monitor (e.g. not the currently selected monitor input), and also allows any other USB-C output device to be easily plugged in. To hold the cables I just used a set of white basic cable management clips. The right-most monitor also has a new webcam (with mic) on top.\n\nCost\n\nThis is a tricky one, since the total varies massively if I include the cost of the house!\n\n\n  £880: Laptop (Lenovo Thinkbook 16p)\n  £500: Standing desk (Flexispot E7)\n  £180: Chair (IKEA Markus)\n  £50: Webcam (Anker C200)\n  £15: Extension leads\n  £15: Laptop / cable mounting\n  Life savings: House!\n\n\nSo, yep, around £1.5k, but with the majority going towards a far more powerful machine and standing desk it seems worth it. Comparing the “new” images at the start of this post with the bonus images below shows how much more appealing the new setup is, helping me be productive and happy.\n\nBonus images\n\n\n  \n    \n      Moving in\n      Old PC setup\n      Floating PC\n    \n    \n      \n      \n      \n    \n  \n\n\n\n  \n    \n      Underneath front of desk\n      Underneath back of desk\n      All screens on whilst setting up\n    \n    \n      \n      \n      \n    \n  \n\n\nConclusion\n\nI’m really, really happy with my two-laptop desk creation, and proud of the creative problem-solving it required! It was a fun mixture of technical challenges (all the monitor connections) and physical challenges (mounting laptops). Of course, it isn’t perfect, so if we consider this version 3, I’m looking forward to version 4.\n\nThe current (minor) issues are:\n\n  My work machine can use 3 monitors, but my personal machine cannot.\n  Due to my laptop’s proprietary 230W(!) charger at the back, the laptop sticks out slightly more than anticipated. Perhaps a right angle adapter can be created, solving this.\n  I have to manually send machines to sleep, otherwise they could easily stay on for days unnoticed. This can probably be solved in power settings.\n  I can no longer use my fingerprint readers, and whilst the laptops both wake up when the wireless keyboard is connected, I have to type the password / PIN.\n\n"
    } ,
  
    {
      "tags"     : "Search, Jekyll",
      "title"    : "Using SimpleJekyllSearch for easy and quick site searching",
      "excerpt"  : "Historically, my Jekyll sites have always had a very slow search feature. Recently I updated minimaJake to use SimpleJekyllSearch, and now it’s almost instant (99.5% reduction in time taken) and easy to customise! Here’s some more detail on how it works, how to implement it, and some further improvements I’d love to try.\n",
      "url"      : "/using-simplejekyllsearch-for-easy-and-quick-site-search/",
      "date"     : "Feb 25, 2023",
      "content"  : "Historically, my Jekyll sites have always had a very slow search feature. Recently I updated minimaJake to use SimpleJekyllSearch, and now it’s almost instant (99.5% reduction in time taken) and easy to customise! Here’s some more detail on how it works, how to implement it, and some further improvements I’d love to try.\n\nBefore &amp; after\n\nThis change brings a lot of visual improvements, but they were technically possible before, just tricky. Far more significant are the massive performance improvements!\n\nOn a bad connection, loading the search page would completely block the UI for over 7 seconds. Now, it’s… 30 ms! That’s an almost unbelievable 99.5% decrease in page loading time, and doesn’t even factor in the fact that the search is now per-keystroke, instead of waiting for enter to be pressed.\n\n\n  \n    \n      Before (v1.0.2)\n      After (v1.0.3)\n    \n    \n      \n      \n    \n    \n      \n      \n    \n  \n\n\nIntroducing SimpleJekyllSearch\n\nIn a recent post I laid out some of the problems with my current search, and proposed a better approach:\n\n\n  Eventually I’d like to export the text from all posts to a static file during compilation / publishing, then just use this for future lookups instead of essentially regenerating this data every time the page is loaded.\n\n\nAnd, luckily, this is pretty much exactly what SimpleJekyllSearch does. This library has unfortunately been deprecated in 2022, and hasn’t had major development in a couple of years, but despite this seems to work perfectly. It consists of 2 parts:\n\n\n  Generating a search.json by just looping through each post and outputting searchable data into a JSON object.\n  Providing a configurable JavaScript helper that accepts result templates and element identifiers, then does all the hard work.\n\n\nImplementing SimpleJekyllSearch\n\nCreating searchable posts\n\nFirst, we need to provide a list of all our posts (e.g. as posts.json), complete with the searchable fields. This can be edited to suit your needs, minimaJake tidies up the repo’s example to include post excerpts, format dates better, and avoid character encoding issues:\n\n---\nlayout: none\n---\n[\n  {% for post in site.posts %}\n    {\n      \"title\"    : {{ post.title | jsonify | strip_html }},\n      \"tags\"     : \"{{ post.tags | join: ', ' }}\",\n      \"url\"      : \"{{ post.url }}\",\n      \"date\"     : \"{{ post.date | date: \"%b %-d, %Y\" }}\",\n      \"excerpt\" : {{ post.excerpt | jsonify | strip_html }},\n      \"content\"  : {{ post.content | jsonify | strip_html }}\n    } {% unless forloop.last %},{% endunless %}\n  {% endfor %}\n]\n\n\nAdding HTML elements\n\nNow we need to add the text field and search results area onto the search page, something like:\n\n&lt;form id=\"searchform\"&gt;\n  &lt;p&gt;\n    &lt;input\n      type=\"text\"\n      id=\"search-input\"\n      class=\"form-control\"\n      name=\"q\"\n      value=\"\"\n      autofocus\n    /&gt;\n  &lt;/p&gt;\n&lt;/form&gt;\n&lt;ul id=\"searchresults\" class=\"post-list\"&gt;&lt;/ul&gt;\n\n\nAdding JavaScript\n\nNext, copy either the regular or minified search script into your site, perhaps at /assets/js/search.js.\n\nWe should also include this on the page we want to have the search on, similar to:\n\n&lt;script src=\"/assets/js/search.js\" type=\"text/javascript\"&gt;&lt;/script&gt;\n\n\nFinally, we need to create a SimpleJekyllSearch object, and pass in all the bits we’ve setup:\n\nvar sjs = SimpleJekyllSearch({\n  searchInput: document.getElementById(\"searchform\"),\n  resultsContainer: document.getElementById(\"searchresults\"),\n  json: \"/posts.json\",\n});\n\n\nYou now have a functioning, speedy search!\n\nCustomisation\n\nFor minimaJake, I chose to make a few additional changes to customise the “no results” message, and also format the data properly on the page:\n\n      noResultsText: 'No results found :(',\n      searchResultTemplate: \"&lt;li class='card'&gt;\" +\n          \"&lt;div class='content'&gt;\" +\n            \"&lt;a class='post-link' href='{url}'&gt;{title}&lt;/a&gt;\" +\n            \"&lt;span class='post-meta'&gt;{date} • {tags}&lt;/span&gt;\" +\n            \"&lt;p&gt;{excerpt}&lt;/p&gt;\" +\n          \"&lt;/div&gt;\" +\n        \"&lt;/li&gt;\"\n      }\n\n\nYou might notice that the variables there (e.g. {excerpt}) are just data we output in an earlier stage ({{ post.excerpt | jsonify | strip_html }}). It’s very easy to customise these fields, if you want to search by some sort of custom metadata.\n\nAdditionally, I want the functionality to link directly to a set of results. For example, a search for my name. This is done by checking for a q URL parameter on page load, then if it exists populate &amp; submit the search form:\n\nwindow.addEventListener(\n  \"load\",\n  function () {\n    var searchParam = new URLSearchParams(window.location.search).get(\"q\");\n    if (searchParam != null) {\n      document.getElementById(\"search-input\").value = searchParam;\n      sjs.search(searchParam);\n    }\n    document.getElementById(\"search-input\").placeholder =\n      \"Type your search here...\";\n  },\n  false\n);\n\n\nThis snippet also handles setting a placeholder text, which needs to be done after setting any prefilled search term to avoid a brief flicker.\n\nEnd result\n\nSo, if you follow all these steps what do you get? A complete search page!\n\nThis can then be included elsewhere with just:\n\n{% include custom/search.html %}\n\n\nDrawbacks\n\nWhilst the new search’s performance is undoubtedly better, and there’s far less hacky code around, it isn’t perfect.\n\nThe main drawback I’ve found is that it doesn’t search very selectively. For example if I search “a”, it will just return every single post in date order that contains “a” anywhere in it. This even includes words like “apple”, and doesn’t prioritise tags or titles over the full text of the article.\n\nI’m intending to eventually improve this, by ideally:\n\n\n  Returning all tag matches, then title matches, then excerpt matches, and finally full text matches.\n  Only matching full words, ideally with variants. For example “cat” should return “cats” but not “scatter”.\n  Highlighting where the result has been found, just like when searching in a page on Chrome.\n\n\nI suspect the difficulty in implementing these well varies from tricky (#1) to almost impossible (#2). The library does have templateMiddleware and sortMiddleware so it should be possible with enough work!\n\n2024 update\n\nI implemented #1 &amp; #3 to minimaJake 1.0.4, along with some other features after this article was published! To quote the release notes:\n\n\n  \n    Sorts results according to relevance (tags &gt; title &gt; excerpt &gt; url / date / content)\n    Highlight search term within results (colour needs improving?)\n    Exclude single-character search\n    Display number of results\n    Stops search looking inside character codes (e.g. &amp;)\n  \n\n\nAs suspected, templateMiddleware and sortMiddleware were essential for this, but a few change to the search.js file had to be made to support the concept of “match priority”. Check out the latest versions if you’d like the features listed above:\n\n\n  search.html: The embeddable search HTML, initialises SimpleJekyllSearch.\n  search.js: The core search script.\n\n\nRees Draminski has also implemented the ability to display the relevant section of a post instead of the generic excerpt.\n\nConclusion\n\nOverall I’m happy with this migration, and how consumers of minimaJake now just need to include the search page to have a full-text, instant search available.\n\nThe change to use the same CSS as the homepage (minus the header image) also make the site feel much more coherent, whilst reducing the amount of visual areas that need tweaking. Previously, search was hard to read in dark mode due to hard-coded colours, now it’s all automatic.\n\nHaving a search that works quickly frees up future interesting options, such as having a search available in the header of the site. If you’re looking to add search to your site, give SimpleJekyllSearch a go!\n"
    } ,
  
    {
      "tags"     : "Minima, Jekyll, Liquid",
      "title"    : "Introducing 'minimaJake', a minima theme fork for Jekyll with years of improvements & design changes!",
      "excerpt"  : "Over the last few years I’ve slowly added functionality to the default Jekyll “minima” theme, and recently made it all publicly available. Here’s a description of &amp; integration details for all the new features minimaJake offers, from comments to Ko-fi support to accent colouring!\n",
      "url"      : "/introducing-minimajake-for-jekyll/",
      "date"     : "Feb 7, 2023",
      "content"  : "Over the last few years I’ve slowly added functionality to the default Jekyll “minima” theme, and recently made it all publicly available. Here’s a description of &amp; integration details for all the new features minimaJake offers, from comments to Ko-fi support to accent colouring!\n\nHow to use minimaJake\n\nIf you’re interested in using the theme after seeing all the additions, the easiest way is to just copy this blog’s _config.yml, updating the name / accent colour etc as desired.\n\nAs I write this post the latest version is v1.0.1 (so the import would be remote_theme: JakeSteam/minimaJake@1.0.1), but check the releases page for any updates.\n\nNative features\n\nTable of contents\n\nA table of contents is automatically generated for each post, and uses jekyll-toc.\n\nAll headers (h1 - h6) currently generate a link, but this can be customised by overriding post.html. The table of contents’ width is based on the header length, so it’s a good idea to avoid very long headers (although this is good advice anyway!).\n\nThe “Jump to:” text can be changed in the _config.yml, if it is removed completely then the table of contents will be disabled. The table of contents uses the accent colour for its border, here’s an example from my grey-accented personal site:\n\n\n\nLinkable headers\n\nMousing over each header will make a small link icon appear. This can be used to link directly to any point of the post, and is very powerful when combined with the table of contents. I’m using the Javascriptless jekyll-anchor-headings.\n\nSome extra liquid and CSS has been added to provide properly aligned GitHub style anchor links.\n\n\n\nTag system\n\nEvery post on all of my sites has “tags” AKA topics. These don’t have any strict rules, but I use them to roughly group posts, and make searching for related posts a bit easier. You could also use them for calculating most closely related posts, but minimaJake doesn’t currently.\n\nThey are defined within the front matter of each post very simply:\n\ntags:\n    - Minima\n    - Jekyll\n    - Liquid\n\n\nThe tags.html script is included in the homepage post preview &amp; main post header, and just loops through each tag linking to the search page for that term. The examples below are from my post about a Barcelona trip:\n\n\n  \n    \n      Homepage\n      Post\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nReading time\n\nYou might have also noticed the “reading time” in the above screenshots. This is a super simple script called read_time.html that essentially just divides the number of words by 150, and assumes the article will take that many minutes to read.\n\nThis obviously isn’t very accurate, as some very technical articles might take hours to properly follow, whereas others are simple enough to be skim-read. However, it’s a nice indicator of approximate article length.\n\nPagination\n\nThe “pagination” at the bottom of the home screen (most visible on sites like https://blog.jakelee.co.uk) uses more complex pagination than Jekyll’s default. By default it just creates a link to each page, but this looks pretty bad with more than 3-4 pages. minimaJake’s pagination shows the surrounding few pages, and the first / last. The code is in paginator.html.\n\nI’m having a little trouble finding where exactly the version I use is taken from, but it is somewhere in this tutorial by “Epsi”. The below gif is also from their site, mine currently has no CSS:\n\n\n\nEnd of post CTA\n\nThe bottom of every post contains a CTA (call-to-action) encouraging readers to subscribe to my weekly newsletter. This is just a block of HTML in the config, where removing the line entirely will also hide the CTA.\n\n\n\nSocial &amp; meta link system\n\nWhilst I recently wrote a detailed guide to adding links to minima’s social link system, I actually use a modified version for my sites.\n\nBy default, minima supports a list of clickable buttons at the bottom of the page. This is OK, but I wanted a column of “meta” links (email, repo, RSS) inside the footer. Currently, here’s how it works:\n\n\n  Social links are defined in _config.yml, with the presence of user_title determining where the link should appear:\n\n\n    # No user_title set, will appear at bottom:\n    - { platform: twitter, user_url: \"https://www.twitter.com/JakeLeeUK\" }\n\n    # user_title is set, will be shown in meta column:\n    - { platform: email, user_url: \"mailto:minima@jakelee.co.uk\", user_title: \"minima@jakelee.co.uk\" }\n\n\n\n  Every page includes the footer, and the footer includes social.html and meta.html.\n  These are identical, except social.html creates a social-item.html for each social link, whilst meta.html creates a meta-item.html for each meta link.\n\n\nI have 4 links in each, creating these two blocks of links:\n\n\n  \n    \n      Meta links\n      Social links\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nThird party integrations\n\nlunr.js search\n\nWhilst minimaJake does include a search script, a search.md page is needed to surface this functionality (e.g. this site’s search page).\n\nThis search.html script can be very slow to load (but provides almost instant responses), hence why it isn’t included in every page. It very hackily loads every single post into a Javascript variable, then searches through those for your term! It uses lunr.js, with some extra styling &amp; Javascript on top.\n\nOne additional feature is the ability to link to a specific term (example), this just simulates a search action if the URL parameter is set.\n\nEventually I’d like to export the text from all posts to a static file during compilation / publishing, then just use this for future lookups instead of essentially regenerating this data every time the page is loaded.\n\n\n\nGiscus comments\n\nI’ve written about Giscus before, and a full setup tutorial is included there.\n\nIn minimaJake all the variables are set in the _config.yml, and if they are removed from the config the comments functionality will be disabled.\n\n\n\nKo-fi donations\n\nMy internet history site uses Ko-fi for donations / commissions. Both floating &amp; fixed buttons are used, and their text / Ko-fo target can of course be customised via _config.yml. As always, deleting them from the config will disable the feature.\n\nThe fixed button appears at the end of each post (after CTA, before Giscus comments), and can also be included manually anywhere with:\n\n{%- include custom/donatebutton.html -%}\n\n\n\n  \n    \n      Floating button\n      Fixed button\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nDesign changes\n\nBanner images\n\nPerhaps the most striking change when opening a minimaJake site vs a minima site is there are banner images for every post!\n\nThese are defined in a post’s front matter using image: /assets/images/2023/minimajake.png, then included on both on the homepage and the post itself. Clicking the image opens a full-size version of it.\n\nI really, really like this functionality, and it was one of the first things I added. With the image, each post becomes more than just text, and I find even a simple screenshot of code instantly makes the most more appealing.\n\nBanner images are rendered onscreen at 768px x 180px. Despite this, I recommend adding extra off-screen content to the top and bottom, making the image less rectangular, and also making the image larger than necessary and letting the browser scale it down. This will encourage social media sites to provide a rich preview, and make the post more appealing.\n\nIn the example below, a full-screen screenshot was used. This meant the image met Twitter’s recommended sizes, but was heavily cropped for the blog’s actual header:\n\n\n  \n    \n      Actual image\n      Twitter preview\n      Blog preview\n    \n  \n  \n    \n      \n      \n      \n    \n  \n\n\nAccent colours\n\nFinally, each site has its own “accent colour”, also defined in the _config.yml.\n\nThis is used for the borders around post “cards”, table of contents border, a strip at the top of the site, and mouseover colour for the footer links. Currently it is only used occasionally, but it helps give each site a distinct feel whilst still being minimalist and attractive:\n\n\n\nUpcoming changes\n\nNow that a shared theme is used across all my sites, it’s significantly easier to make improvements. Here’s a few of the planned improvements I’m hoping to work on soon, roughly in order of priority:\n\n\n  Tidy up dark mode now that it is supported, e.g. adjusting Giscus theme to match.\n  Use the accent colour more heavily, perhaps introducing the ability to have a different accent colour in dark mode.\n  Create a “site picker” bar, to show that all my sites are connected, and that there’s plenty of posts!\n  Optimise search enough to include the functionality on every page in the header.\n  Publicise / document the theme better. One option is to use the current showcase site to document updates to the theme, instead of cluttering this blog.\n\n\nConclusion\n\nOverall I’m surprised how many things I’ve actually added to Minima over the years, each of them feels like such basic functionality that I forget they aren’t included!\n\nOf course, adding functionality somewhat goes against what Minima is aiming to be: A default, no-frills theme. However, I believe minimaJake fills a crucial role: minimalist, whilst still having the option for advanced functionality.\n\nIf you use minimaJake or have any feature requests / issues please let me know, it’s very much a labour of love so I’m always looking to improve it!\n"
    } ,
  
    {
      "tags"     : "Jekyll, Minima",
      "title"    : "How I merged my 3 Jekyll site codebases into 1, as a public theme",
      "excerpt"  : "Up until last week I had 3 blogs, each with their own GitHub repositories, copies of code, CSS modifications, and overall configuration. Whilst this worked, it was impossible to maintain or scale up. In this post I’ll describe how I merged all of these into 1, whilst also updating to the latest Minima version and making future improvements much easier to implement.\n",
      "url"      : "/merging-multiple-jekyll-codebases-into-one/",
      "date"     : "Feb 3, 2023",
      "content"  : "Up until last week I had 3 blogs, each with their own GitHub repositories, copies of code, CSS modifications, and overall configuration. Whilst this worked, it was impossible to maintain or scale up. In this post I’ll describe how I merged all of these into 1, whilst also updating to the latest Minima version and making future improvements much easier to implement.\n\nThe situation\n\nSo how did I end up with 3 almost identical codebases? Well, I had my programming blog (this one!), then added my personal blog, and more recent an internet history blog. Both of these spin-off projects were initially just little experiments, so weren’t worth creating an elegant solution for.\n\nTo summarise, currently each blog has:\n\n\n  Posts / images. All the actual blog content, displayed according to the:\n  Custom code / CSS. Features like search, in addition to custom site colours, all built on top of:\n  Minima theme. The 2.5.1 Minima theme code.\n\n\n\n\nHowever, since I am now considering a 4th blog, it was time to bite the bullet and actually fix the duplication problem!\n\nThe problem\n\nYou might be asking since the blogs were thriving in their own codebases, what’s the issue?\n\nDuplicate work\n\nWell, day to day it was fine. I could write a new post, add images, do whatever I needed to nice and easily. The problem came when I wanted to make a CSS fix, or add a new feature to the site. I’d have to manually copy blocks of code between the 3 sites, which is a recipe for disaster.\n\nEven with the very limited feature disparity between sites (e.g. one site has a donation button, the rest don’t), the few additional lines of code cause line numbers to differ, making future copy &amp; pasting error-prone.\n\nHard to migrate\n\nAdditionally, I wanted to migrate to the unreleased Minima 3.0.0 theme. It includes a few quality-of-life changes, as well as built-in automatic dark mode functionality. This would require quite a few changes to the site, and doing that 3 times with slightly different codebases would undoubtedly have introduced issues.\n\nThe solution\n\nMy target end state is no duplication. This is likely to be achieved by merging the Minima theme &amp; custom code blocks from the diagram earlier, leaving just a per-site config and any posts. I also want to:\n\n\n  Be able to configure my blogs (accent colour, title, features, etc) in one file each.\n  Only need to add new functionality in one place.\n  Be able to easily “update” to the latest shared codebase version on a per-blog basis at the time I choose.\n  Be able to push changes to the core codebase without any risk of them ending up on a real site.\n\n\nSince I was making significant changes and merging codebases, I also decided to update to the unreleased Minima 3!\n\nWhat didn’t work\n\nWhilst I knew whatever approach I used would need some sort of “config” file per site (instead of the current custom code on every side), I wasn’t quite sure how to apply that config.\n\nForks\n\nOne of my first thoughts was to restructure my repositories to logically represent the code inheritance. So, my “core” codebase would be a GitHub fork off the actual Minima repo, and each blog would be a fork off my “core” codebase.\n\nInitially this seemed promising, as it would mean each repository clearly shows what it is based on, and newly contributed changes could be pulled from the upstream Minima repo into my blogs directly.\n\nUnfortunately, it would have required recreating all of my repositories as forks, allowing them to be “linked” to each other on GitHub. This would have required reconfiguring all the GitHub pages setup, whilst also forcing me to regularly merge between repositories. Finally, whilst not a dealbreaker, none of my commits would have “counted” as a contribution, since GitHub doesn’t count commits in a fork. Ultimately I realised a chain of forks maybe wasn’t what I wanted.\n\n\n\nSubmodules\n\nNext, I considered pulling all the shared code into one repository, then including this as a git submodule within my blog repositories. This was perhaps a more accurate logical mapping, since the shared code was a “part” of the overall blog. Additionally, updating would be easy, just update the submodule commit.\n\nAgain, this idea didn’t end up working. The shared files (e.g. _includes) are in the same directory level as the posts themselves, whereas a submodule needs to be inside a dedicated folder. Whilst I could have reconfigured the build system to look for the posts somewhere else, I’ve worked in a project that depended on submodules before, and it wasn’t very fun!\n\n\n\nWhat did work\n\nSo, I’d tried a couple of git features I knew, and neither of them had been quite right. I put the project aside for a day or two, and tried to come at it from a new angle. Whilst researching how to use the “new” unreleased version of Minima, I discovered Jekyll had the ability to load the theme from a GitHub repository using remote_theme. This gives a similar effect to a submodule.\n\nIn my original architecture, I’m layering all my custom code and config on top of the Minima theme. What if… my custom code is included in a theme? What if, instead of using the default theme and layering changes on top, I just used my own customised copy of it to begin with?\n\nWell, that works perfectly! I’ve called it minimaJake, and I’ll write about it properly in a future post.\n\n\n\nNow, my (and anyone else’s) sites can use the shared theme and all its features just by adding remote_theme: JakeSteam/minimaJake to their _config.yml.\n\nThis has a number of advantages:\n\n\n  The solution uses built-in Jekyll features (well, with a supported plugin), avoiding any weird configuration hacking.\n  Each blog’s repository (e.g. programming blog) only contains the assets it needs (posts, images, configuration, any static pages).\n  The “merged” theme is available to the public, in case anyone wants to use features from my blogs. There’s also a chance others might want to help add new features.\n  The remote theme system is aware of GitHub releases. This means I can peg all my sites to v1.0.0 of minimaJake, safely make &amp; push changes to the repository, and eventually release v1.0.1 when it is stable.\n\n\nConclusion\n\nOverall, the migration went much more smoothly than I expected. Once I had the first site configured, the other sites took almost no effort at all, showing the flexibility of the theme system. I’m very, very appreciative of how open the Jekyll theming and configuration system is, whereby it takes almost no effort to add new feature toggles, design changes, or config variables.\n\nIn some ways, this migration reminds me of my move from Wordpress to Jekyll almost a year ago. Whilst I previously avoided improving the codebase due to the messy nature of the duplicated code, recently I’ve had endless ideas about improvements all the sites would benefit from.\n\nDue to this, there’s plenty of next steps I’m excited for! First, I want to write proper documentation for minimaJake and all the blogs that use it. Right now they just have basic documentation from when I was learning Jekyll, not particularly helpful for anyone who has spent 5 minutes with Jekyll! Next, some way to navigate easily between my growing collection of sites…\n\nPS: This is my first post using Excalidraw for diagrams, it’s great!\n\nNotes\n\nActions taken\n\nTo summarise, here’s the actual changes I made:\n\n\n  Checked out the official Minima repo.\n  Deleted everything I didn’t need (e.g. GitHub Actions scripts).\n  Pushed to a new repository.\n  Copied across every feature &amp; CSS change from my current sites, in a config-controlled way.\n  For each site repository, deleted everything except posts &amp; related assets, then set up the _config.yml file.\n  Checked this local site matched the current live site, and published.\n\n\nDifferences to Minima\n\nThere will be a follow-up post with all the changes minimaJake includes, here’s a high-level overview:\n\nNative (liquid) features:\n\n\n  Table of contents\n  Linkable headers\n  Tag system\n  End of post call to action\n  Social &amp; meta link system in footer\n\n\nThird party features:\n\n\n  Search (via lunr.js)\n  Giscus comments\n  Configurable Ko-fi donation button &amp; floating prompt\n\n\nDesign changes:\n\n\n  Banner images\n  Accent colour system\n\n\nSimple config\n\nIn my programming blog’s config file for example, all the commonly configured options are at the very top:\n\n# Basic site setup\nremote_theme: JakeSteam/minimaJake@1.0.1\ntitle: Jake Lee on Software\ndescription: In-depth ad-free articles about software development, Android, and the internet\naccent_colour: \"#2a7ae2\"\n\n# Optional native feature customisation (delete to turn off)\ntable_of_contents_header: \"Jump to:\"\npost_end_promo: &lt;i&gt;&lt;b&gt;Enjoyed this article? You'll like \"&lt;a href=\"https://jakeweeklee.substack.com\"&gt;Jake Week Lee&lt;/a&gt;\", a weekly newsletter of articles &amp; found media!&lt;/b&gt;&lt;/i&gt;\ngoogle_analytics: G-99X0QYL39T\n\n# Third party feature customisation (delete to turn off)\ngiscus_repo: JakeSteam/blog-programming\ngiscus_repo_id: MDEwOlJlcG9zaXRvcnkzNTk5Mzc1OTM=\ngiscus_category: Comments\ngiscus_category_id: DIC_kwDOFXQ2Oc4CQ06o\n\n\nTo start up an instance of a “minimaJake” blog, all that needs changing are the title, description, and accent colour, as well as deleting any unwanted features. This makes it super flexible, for both myself and any third party users.\n"
    } ,
  
    {
      "tags"     : "Minima, Web, SVG",
      "title"    : "How to add a new social media link to Minima 2.5.1 and latest unreleased version (3.0.0)",
      "excerpt"  : "Recently I migrated all of my Jekyll sites from Minima 2.5.1 (updated August 2019) to the latest version on GitHub (updated January 2023). This came with lots of new features, but also changed how social links are handled. In this post I’ll cover both the old and new method for adding new social links, as well as the technical details.\n",
      "url"      : "/adding-new-social-media-link-to-minima/",
      "date"     : "Feb 1, 2023",
      "content"  : "Recently I migrated all of my Jekyll sites from Minima 2.5.1 (updated August 2019) to the latest version on GitHub (updated January 2023). This came with lots of new features, but also changed how social links are handled. In this post I’ll cover both the old and new method for adding new social links, as well as the technical details.\n\nBefore we get started, here is the Minima 2.5.1 sourcecode, and here is the latest source code. Minima inexplicably hasn’t had a new release in over 3 years, so the latest codebase has diverged from the latest release.\n\nWhich Minima version do I have?\n\nIf you’ve just set up your Jekyll blog, you have Minima 2.5.1.\n\nIf you’ve manually set remote_theme=jekyll/minima in your _config.yml, you have the unreleased Minima 3.0.0.\n\nAdding social link in Minima 2.5.1\n\nAdding a new social link is pretty straightforward, but there’s no official guide! You can see an example of this process in a commit from when I added a Substack link to my site. Note that the SVG is minimised (all on one line), but you can still see the &lt;symbol&gt;.\n\nSteps\n\n\n  Get an SVG.\n    \n      In this example I’ll use FontAwesome’s “coins” icon, obviously make sure you have permission to use your SVG!\n    \n  \n  Change the SVG into a named symbol.\n    \n      Open in any text editor.\n      Remove everything except the &lt;svg&gt; and &lt;path&gt; sections.\n      Change the &lt;svg and &lt;/svg&gt; to &lt;symbol and &lt;/symbol&gt;.\n      Delete everything from the &lt;symbol except viewport=\" ... \", and add an id=\" ... \".\n      Delete everything from the &lt;path except d=\" ... \".\n\n    \n  \n  Add SVG to combined image.\n    \n      Put the SVG code at the bottom of assets/minima-social-icons.svg, just before &lt;/svg&gt;.\n\n    \n  \n  Add social link to footer.\n    \n      Inside social.html, copy an existing line (e.g. YouTube) and replace the URL &amp; variable names (e.g. youtube_username to coins_username).\n      Don’t forget to update the minima-social-icons.svg#youtube to your ID from step 2.\n    \n  \n  Add to _config.yml.\n    \n      For example, these coins might be coins_username: Jake123 and coins_url: https://example.com/Jake123.\n    \n  \n  Relaunch your site, your new social link should be there!\n\n\nExplanation\n\nWhilst the process of adding a new social icon to Minima 2.5.1 is pretty convoluted, at least the use of it is simple!\n\n\n  footer.html includes social.html.\n  social.html checks each social source to see if it is defined in _config.yml, and displays the username &amp; URL if so.\n  Additionally, social.html uses the symbol’s id to fetch a specific section of the minima-social-icons.svg, e.g. #youtube.\n\n\nAdding social link to latest Minima\n\nWhilst there is a guide on the project’s readme, it can be a little tricky to know how to resize the image and handle it correctly.\n\nSteps\n\n\n  Get an SVG.\n    \n      In this example I’ll use FontAwesome’s “coins” icon, obviously make sure you have permission to use your SVG!\n    \n  \n  Resize to be 16x16 square.\n    \n      I used “iloveimg”, but if you have a proper SVG editor feel free to use it.\n      Set the width &amp; height px to 16 (since SVGs are scalable there won’t be any loss of quality) then download.\n      It’s OK if it’s not square by a pixel or two, but it’s worth the effort if possible!\n    \n  \n  Remove everything except &lt;path&gt; data.\n    \n      Open in any text editor.\n      Check inside the &lt;svg&gt; element for viewBox=\"0 0 16 16\", this means it’s the correct size.\n      Delete everything outside of the &lt;path&gt; tag, and the style=\" ... \" bit, then save.\n\n    \n  \n  Put this SVG in _includes/social-icons/.\n  Add to _config.yml.\n    \n      For example, these coins might be - { platform: coins,  user_url: \"https://example.com/mycoins\" }\n    \n  \n  Relaunch your site, your new social link should be there!\n\n\nExplanation\n\nMinima 3 changed how social icons are used. Instead of being manually added into one big SVG, they are now dynamically built up during compile time.\n\nPersonally I think this is overly convoluted, and would be better served by just displaying standard SVG icons, or using the slightly simpler previous system. The justifications in the PR do make sense, but for a “minimal” theme it’s a totally unnecessary complication (as was the previous system). Adding a new clickable icon shouldn’t include this much complexity:\n\nGenerating the combined SVG\n\n\n  minima-social-icons.liquid loops through the social_links defined in _config.yml, and includes svg_symbol.html once per social link.\n  svg_symbol.html builds up a 16x16 section of the overall SVG, including the social link’s icon by name.\n\n\nUsing the combined SVG\n\n\n  _includes/footer.html (the site’s footer) includes social.html.\n  social.html loops through the social_links defined in _config.yml, and includes social-item.html once per social link.\n  social-item.html looks in the minima-social-icons.svg file for an SVG with the social link’s name, and displays a clickable icon.\n\n"
    } ,
  
    {
      "tags"     : "GitHub, Jekyll",
      "title"    : "An introduction to GitHub & Jekyll's footnote functionality, and finding its limits",
      "excerpt"  : "Way back in September 2021, GitHub added support for footnotes, an intuitive way to add footnotes or references to a page. The “Kramdown” parser on Jekyll has also supported footnotes for a decade. But… what are they actually capable of?\n",
      "url"      : "/footnote-experiments-on-github-and-jekyll/",
      "date"     : "Jan 22, 2023",
      "content"  : "Way back in September 2021, GitHub added support for footnotes, an intuitive way to add footnotes or references to a page. The “Kramdown” parser on Jekyll has also supported footnotes for a decade. But… what are they actually capable of?\n\nJekyll’s Kramdown parser has excellent documentation for the permitted uses. My experimentation suggests that this documentation is 100% accurate. GitHub’s documentation is much simpler, but also describes the essentials accurately.\n\nIntro to footnotes\n\nFootnotes in markdown are an extremely useful yet niche functionality that almost nobody actually uses. Whilst they are usually used to provide additional non-essential information1, in a more academic context they can be used to cite sources. For example, on my Internet History blog I always provide links to source material, causing articles to easily have 20+ sources. Any non-automated solution would be painful to maintain, so Markdown footnotes are a lifesaver.\n\nTo use a footnote, you need two components:\n\n\n  The marker: This looks [^like-this], and is placed within the main text where the footnote should be linked from. This will be converted into a small auto-numbered link looking similar to: [1].\n  The definition: This looks [^like-this]: Abc def, and can be placed anywhere within the document. It defines the contents of the footnote, and automatically links back to any parts of the text that reference it.\n\n\nAll of a page’s footnotes are merged together &amp; numbered automatically during the publishing process. For more complex posts, I usually use named footnotes, and place the definitions at the end of the section containing the marker.\n\nIf you’d like a more detailed &amp; step-by-step explanation of the basics of footnotes in Markdown, Linux Hint has an excellent guide.\n\nFootnote functionality\n\nSo, footnotes are easy to use, and improve Markdown articles. What are their limits?\n\nURL additions\n\nThe footnote marker and definition both work by adding an identifier to the URL when clicked.\n\nOn Jekyll these are #fn:[footnote] for the marker, and #fnref:[footnote] for the definition.\n\nOn GitHub these are #user-content-fn-[footnote]-[id] for the marker, and #user-content-fnref-[footnote]-[id] for the definition. This ID appears to be randomly generated for each footnote.\n\nSupported characters\n\nWhilst many online examples use basic numerical footnotes (e.g. [^1]), text footnotes (e.g. [^example]) also work! What else is allowed as part of a footnote identifier?\n\n\n  \n    \n      Characters\n      Example\n      Supported on GitHub\n      Supported on Jekyll\n    \n  \n  \n    \n      Alphanumeric\n      [^abc]\n      All letters &amp; numbers\n      All letters and numbers\n    \n    \n      Long text\n      [^abc … abc]\n      Up to 1000 characters\n      Above 16,000 characters, no limit found\n    \n    \n      Punctuation\n      [^!\"£$%^&amp;*()_+-=]\n      All are valid\n      Only -, and only after an alphanumeric character\n    \n    \n      Meta punctuation\n      [^\\[]\n      Escaped [ is OK, but escaped ] or : are not\n      None are permitted\n    \n    \n      Spaces\n      [^ ]\n      Non-breaking spaces can go at start / middle / end (or be the only content), regular spaces cannot go anywhere\n      None are permitted\n    \n    \n      Non-latin characters\n      [^Приветこんにちはأهلا]\n      Russian, Japanese, and Arabic all work\n      No non-latin characters work, even é\n    \n  \n\n\nSupported contents\n\nOkay, so now we know what can go in a footnote identifier, but what can go into the footnote itself?\n\nIt turns out… pretty much anything works, so long as it is after the footnote definition and preceded by 4 spaces!\n\nJekyll requires some types of content to have an empty line before they will render correctly, but ultimately seems to support all functionality.\n\n\n  \n    \n      Test\n      Supported on GitHub\n      Supported on Jekyll\n    \n  \n  \n    \n      Multiline\n      Yes\n      Yes\n    \n    \n      Table\n      Yes\n      Yes\n    \n    \n      List\n      Yes\n      Yes\n    \n    \n      Quote\n      Yes\n      Yes\n    \n    \n      Code block\n      Yes\n      Yes\n    \n  \n\n\nSelf-referential\n\nAdmittedly this section is me intentionally trying to “trick” the footnote generator, but here we go! Footnotes can reference footnotes (e.g. [^example]: some text[^example2]) and function correctly. They can even reference themselves, although GitHub (left) and Jekyll (right) treat this edge case slightly differently:\n\n\n\nFootnotes can also be defined before or after they are used.\n\nAutolinking\n\nWhilst writing this post I discovered a feature I wish I’d known months ago, especially whilst writing my reference-heavy internet history posts. Markdown supports URL auto-linking, to do this just add &lt; and &gt; around a URL. This will turn https://example.com into https://example.com.\n\nThis autolinking syntax is only required for Jekyll, as GitHub automatically makes all links clickable by default.\n\nConclusion\n\nUltimately, I didn’t discover anything particularly shocking about footnotes, except that GitHub is way more lenient with the identifiers than Jekyll! That being said, the discovery of autolinking is a good example of why reading the documentation is often helpful, even if it doesn’t solve the immediate problem.\n\nPerhaps there’s no greater indicator of how underutilised footnotes are than a Google search for “jekyll footnotes” returning… 114 results. “footnotes in jekyll” similarly returns just 10. Most of these results are for now unnecessary third party plugins2, or simplistic / broken guides3, but at least “markdown footnotes” returns 2.5k results!\n\nReferences\n\n  \n    \n      Non-essential information such as the fact that Grammarly describes footnotes as\n      \n        Footnotes are small notations at the bottom of a page that provide additional information or cite the source of a passage in the page’s text.\n4\n      \n      &#8617;\n    \n    \n      https://github.com/orangejulius/jekyll-footnotes &#8617;\n    \n    \n      https://www.kylealwyn.com/blog/how-to-add-footnotes-markdown &#8617;\n    \n    \n      https://www.grammarly.com/blog/footnotes/ &#8617;\n    \n  \n\n"
    } ,
  
    {
      "tags"     : "Jekyll, GitHub, Markdown",
      "title"    : "How to display complex content (lists, code, images) inside a table reliably in Markdown / GitHub / Jekyll",
      "excerpt"  : "As anyone who writes in Markdown knows, it’s a very concise and easy way to write almost all content. However, tables can be a little bit awkward, especially if it includes multi-line content like a list! Here’s a quick comparison of techniques that can be used to solve this, and whether they work in plain Markdown, GitHub, and Jekyll blogs.\n",
      "url"      : "/displaying-complex-content-inside-jekyll-tables/",
      "date"     : "Jan 17, 2023",
      "content"  : "As anyone who writes in Markdown knows, it’s a very concise and easy way to write almost all content. However, tables can be a little bit awkward, especially if it includes multi-line content like a list! Here’s a quick comparison of techniques that can be used to solve this, and whether they work in plain Markdown, GitHub, and Jekyll blogs.\n\nSummary of results\n\nThe table below shows a results summary of which technique works where, unfortunately there’s no “one solution works everywhere” answer! A one sentence summary would be:\n\n  Either tolerate a fully HTML table, or use {::nomarkdown} on Jekyll &amp; HTML content on GitHub.\n\n\n\n  \n    \n      Technique\n      Markdown\n      GitHub\n      Jekyll\n    \n  \n  \n    \n      Using no technique\n      ❌\n      ❌\n      ❌\n    \n    \n      Using HTML for entire table\n      ✅\n      ✅\n      ✅\n    \n    \n      Using HTML for content only\n      ✅\n      ✅\n      ❌\n    \n    \n      Using {::nomarkdown} and HTML\n      ❌\n      ❌\n      ✅\n    \n  \n\n\nThe following sections will show the code &amp; detailed results of this testing along with a bit of commentary. The table’s appearance was checked for accuracy in the following scenarios:\n\n\n  Markdown: Whether the table renders correctly in my markdown editor: Visual Studio Code with GitHub styled markdown.\n  GitHub: Whether the table renders correctly on GitHub.\n  Jekyll: Whether the table renders correctly on Jekyll (this post!).\n\n\nNo technique\n\nUnsurprisingly, using regular Markdown inside a table causes impressively bad formatting issues, with code and list formatting especially chaotic.\n\nCode\n\n| Content | Example |\n| --- | --- |\n| List | * aaa\n* bbb |\n| Code block | \\```\nccc \n\\``` | \n| Image | ![](/assets/images/2023/tables-example.png) |\n\n\nResult\n\n| Content | Example |\n| — | — |\n| List | * aaa\n\n  bbb |\n| Code block | ```\nccc\n    \n\n    | Image |  |\n  \n\n\nFully HTML table\n\nThis works almost perfectly! Lists are easy to work with, code blocks can be as complex as they need to be, and everything is nice and readable.\n\nThe downside is using horrifically verbose HTML tables (24 lines vs 5 lines), and having to negotiate HTML’s awareness of whitespace (notice the code block’s odd formatting).\n\nCode\n\n&lt;table&gt;\n    &lt;tr&gt;\n        &lt;th&gt;Content&lt;/th&gt;\n        &lt;th&gt;Example&lt;/th&gt;\n    &lt;/tr&gt;\n    &lt;tr&gt;\n        &lt;td&gt;List&lt;/td&gt;\n        &lt;td&gt;&lt;ul&gt;\n            &lt;li&gt;aaa&lt;/li&gt;\n            &lt;li&gt;bbb&lt;/li&gt;\n        &lt;/ul&gt;&lt;/td&gt;\n    &lt;/tr&gt;\n    &lt;tr&gt;\n        &lt;td&gt;Code block&lt;/td&gt;\n        &lt;td&gt;\n            &lt;pre&gt;&lt;code&gt;\nccc\n            &lt;/code&gt;&lt;/pre&gt;\n        &lt;/td&gt;\n    &lt;/tr&gt;\n    &lt;tr&gt;\n        &lt;td&gt;Image&lt;/td&gt;\n        &lt;td&gt;&lt;img src=\"/assets/images/2023/tables-example.png\"&gt;&lt;/td&gt;\n    &lt;/tr&gt;\n&lt;/table&gt;\n\n\nResult\n\n\n    \n        Content\n        Example\n    \n    \n        List\n        \n            aaa\n            bbb\n        \n    \n    \n        Code block\n        \n            \nccc\n            \n        \n    \n    \n        Image\n        \n    \n\n\nHTML content only\n\nConverting the markdown content into HTML works well on GitHub (besides the mess of having complex HTML all on one line). However, on Jekyll it falls apart, showing the raw HTML instead for most content types.\n\nThis tripped me up recently, when using a list of video examples in a post worked perfectly until I actually previewed the post.\n\nCode\n\n| Content | Example |\n| --- | --- |\n| List | &lt;ul&gt;&lt;li&gt;aaa&lt;/li&gt;&lt;li&gt;bbb&lt;/li&gt;&lt;ul&gt; |\n| Code block | &lt;pre&gt;&lt;code&gt;ccc&lt;/code&gt;&lt;/pre&gt; |\n| Image | &lt;img src=\"/assets/images/2023/tables-example.png\"&gt; |\n\n\nResult\n\n\n  \n    \n      Content\n      Example\n    \n  \n  \n    \n      List\n      &lt;ul&gt;&lt;li&gt;aaa&lt;/li&gt;&lt;li&gt;bbb&lt;/li&gt;&lt;ul&gt;\n    \n    \n      Code block\n      &lt;pre&gt;ccc&lt;/pre&gt;\n    \n    \n      Image\n      \n    \n  \n\n\n::nomarkdown &amp; HTML\n\nLuckily, I found this answer showing how the {::nomarkdown} tag makes the HTML content be formatted correctly again.\n\nWhilst this does work perfectly, the raw code is pretty messy to look at!\n\nCode\n\n| Content | Example |\n| --- | --- |\n| List | {::nomarkdown}&lt;ul&gt;&lt;li&gt;aaa&lt;/li&gt;&lt;li&gt;bbb&lt;/li&gt;&lt;ul&gt;{:/} |\n| Code block | {::nomarkdown}&lt;pre&gt;&lt;code&gt;ccc&lt;/code&gt;&lt;/pre&gt;{:/} |\n| Image | {::nomarkdown}&lt;img src=\"/assets/images/2023/tables-example.png\"&gt;{:/} |\n\n\nResult\n\n\n  \n    \n      Content\n      Example\n    \n  \n  \n    \n      List\n      aaabbb\n    \n    \n      Code block\n      ccc\n    \n    \n      Image\n      \n    \n  \n\n"
    } ,
  
    {
      "tags"     : "RuneScape, Gaming, Archiving",
      "title"    : "How and why the RuneScape Archive project scours old hard drives to preserve MMORPG history and restore lost media",
      "excerpt"  : "Like a lot of people my age, I got really into RuneScape in the 2000s-2010s (maxed acc!), and nostalgia for it is why I originally got into Android development. Unfortunately, Jagex did not keep backups until 2012, so all versions of the game before then are lost… except for old caches on player’s computers! The RuneScape Archive project helps coordinate the recovery effort, and you can help.\n",
      "url"      : "/the-runescape-archives-mission-to-rescue-old-runescape-caches/",
      "date"     : "Jan 9, 2023",
      "content"  : "Like a lot of people my age, I got really into RuneScape in the 2000s-2010s (maxed acc!), and nostalgia for it is why I originally got into Android development. Unfortunately, Jagex did not keep backups until 2012, so all versions of the game before then are lost… except for old caches on player’s computers! The RuneScape Archive project helps coordinate the recovery effort, and you can help.\n\nWhat are the caches?\n\nSo what are these caches? Well, they contain most of the game’s resources (sounds, textures, models, etc) but none of the player’s data or anything sensitive. They are used to reduce loading screens within the game, and are automatically replaced over time as the game updates.\n\nThis means that anyone who regularly plays the game won’t have all of these old caches, only a copy from just before the 5-6 times the location / format has changed over the years, and from their most recent version played.\n\nWhy preserve the caches?\n\n\n  Nostalgia: For many people (myself included) RuneScape is a massive part of their childhood. Being able to preserve the version of the game that has some specific sentimental value is a noble goal.\n  Old School Runescape: This alternate version of the game (AKA 2007scape) is more popular than the main game, and comes almost entirely from a 2007 game backup that was restored in 2013. Having access to caches from a similar time period opens up the possibility of Jagex reusing these assets for future updates.\n  Accessing lost content: In the past, secret items and music were hidden or lost, but they still exist in old game caches.\n  Future uses: Who knows what possibilities hundreds of similar-but-different low-poly game worlds might have in the future! Animating map changes over time? Analysing graphical asset changes over time? The possiblities are endless, but only if these caches are preserved.\n\n\nThe RuneScape Archive\n\nSo, these caches should be saved. But how are The RuneScape Archive planning to make that happen?\n\nWell, it requires a small amount of effort from as many people as possible, to look on old hard drives and try to form a complete archive of these caches for every version of RuneScape. As might be expected, the older versions of the game cache are much more incomplete, with &lt; 6% of 2003’s caches preserved, whilst 75% of 2011’s are.\n\nInterestingly, The RuneScape Archive are also preserving all versions of Old School Runescape, which itself came from an old backup! Luckily these are all pretty much complete, with 80-95% of all 2013-2018 updates preserved, and 100% of all newer caches. Each time the main organiser Hlwys (Hlwys#0641 / u/Hlwys) posts to Reddit (e.g. 2021, 2022, 2023) these numbers improve slightly due to new contributors.\n\nThe current progress is tracked on this Google Sheet, with live updates provided on their Discord server.\n\n\n\nOf course, storing hundreds of cache files full of game assets can get big. Really big. In fact, over 5TB of space is needed to store this ever-growing archive. Or at least, it would be if another project wasn’t helping with storage…\n\nOpenRS2\n\nGraham (Graham#5361) helps organise “OpenRS2 Archive”, a sister project that optimises this 5TB of data into just 125GB. In their own project page’s words:\n\n\n  The archive uses content-addressable storage, converting caches to the client’s native .dat2/.idx format on demand. This provides several benefits: the disk space required to store all available caches is reduced, and groups or XTEA keys missing from one copy of the cache can be sourced automatically from other copies - provided the checksums and version numbers match.\n\n\nIn plain English, this means instead of storing many copies of the same file, OpenRS2 isolates each asset and stores a single copy of it. This also makes checking new caches for missing content much easier!\n\nYou can view the pending cache import queue and the status of each cache, which helps provide an insight into the “behind the scenes” magic that allows this project to exist.\n\nHow can you help?\n\nYou can look on your hard drive for these old caches, and submit them! Even if a copy of your cache already exists, additional copies can sometimes preserve content missing from another copy.\n\nThese caches contain no personal info, just game files.\n\nAutomatically finding\n\nThere is an open source automatic scanning tool that will look for these caches in any version of Windows from 95 to 10. After downloading RunescapeCacheFinder.exe and starting the scan, it will search your disk for any matching caches:\n\n\n\nFor me, this tool outputted a RSCaches.dat file. Opening this up in a text editor and searching for “jagex” revealed I had a 120mb cache in C:\\Users\\Jake\\jagexcache\\runescape\\LIVE from June 2015! Whilst this cache isn’t as important as earlier ones (since Jagex likely have a copy), I still submitted it to the project.\n\nManually finding\n\nOf course, you can also look in the usual directories yourself if you don’t want to run the finder .exe. The cache’s common locations are known, and vary according to the version of RuneScape, however looking manually may miss unusual cache locations (or backups). Additional information on these typical paths can be found on the “Game Data Preservation Project” on RS wiki.\n\nHere are the locations for the highest priority caches:\n\nRuneScape Classic\n\n\n  C:\\.file_store_32\n  C:\\WINDOWS\\.file_store_32\n  C:\\Documents and Settings\\&lt;USERNAME&gt;\\Local Settings\\Temporary Internet Files\n  C:\\WINNT\\Temporary Internet Files\n  C:\\WINDOWS\\cache-93423-17382-59373-28323\n\n\nNote: Before December 2002 RSC caches can be in many places, but always contain mudclient and have the extension .jag. I recommend using the automatic finding tool instead of manually looking.\n\nRuneScape 2 (2003-2006)\n\n\n  C:\\WINDOWS\\.file_store_32\n\n\nOther versions / betas\n\n\n  C:\\WINDOWS\\.jagex_cache_32\n  C:\\Users\\[USERNAME]\\jagexcache\n\n\nNote: The jagexcache folder may be called jagexcache1, jagexcache2, etc.\n\nConclusion\n\nOverall, this project is an excellent example of how previously lost content can sometimes eventually be restored if enough people help out. Whilst the bulk of the archiving and organising work appears to be done by a few key individuals, there are many more helping with various areas, and hundreds if not thousands contributing their caches.\n\n“Completing” the archive is technically possible, but personally I’m unsure that every single version will be found, especially considering hotfixes and other minor updates. However, this is no reason not to try: every cache submitted helps. The organisers are more optimistic, and with almost 50% of caches found, only 150 currently missing caches need to be found! Take a look on your old PCs / laptops for caches, and maybe you can help the archive get one step closer.\n\nIf you have any further questions, RuneScape Archive’s FAQ page might have the answer. Alternatively, the RuneScape Archive Discord is quite active, and the OpenRS2 Discord can help with storage-related questions.\n"
    } ,
  
    {
      "tags"     : "Slack, Jira, Automation",
      "title"    : "Using a Slack workflow to streamline internal bug triaging & Jira ticket creation",
      "excerpt"  : "Like many engineering teams, the Photobox app team lets colleagues from other departments report bugs internally via Slack. To ensure sufficient detail, we use a Slack workflow to standardise bug reporting and simplify Jira ticket raising. Here’s how to implement something similar.\n",
      "url"      : "/using-slack-workflows-for-better-jira-bug-triaging/",
      "date"     : "Dec 31, 2022",
      "content"  : "Like many engineering teams, the Photobox app team lets colleagues from other departments report bugs internally via Slack. To ensure sufficient detail, we use a Slack workflow to standardise bug reporting and simplify Jira ticket raising. Here’s how to implement something similar.\n\nEnd result\n\nSubmitter’s perspective\n\nThe workflow aims to reduce the friction colleagues may face when raising bugs. As all the actions are public, the submitter can easily keep track of any bugs they want to follow the progress of, whilst also being confident that their report has been acted on.\n\nJust as importantly, they can also add any relevant photos / videos / files, and answer any questions the triaging engineer might have whilst trying to reproduce the issue.\n\n\n  \n    \n      Creating\n      Submitting\n      Confirmation\n    \n  \n  \n    \n      \n      \n      \n    \n  \n\n\nEngineer’s perspective\n\nThis semi-automated approach makes the process easier for the engineers / whoever is triaging the reports, by ensuring all the relevant information is provided upfront, and letting it be actioned without leaving Slack. Additionally, any follow-up questions can be asked directly to the bug submitter, avoiding any low quality / out of scope / duplicate bugs unexpectedly appearing in the backlog.\n\n\n  \n    \n      Creating issue\n      Filling in data\n      Confirmation\n    \n  \n  \n    \n      \n      \n      \n    \n  \n\n\nApproach\n\nTo make this approach, we’re going to need to achieve 2 main tasks:\n\n\n  Create a bug report form within Slack.\n  Send this bug report form’s information to Jira.\n\n\nThere are a couple of important caveats with this method, that are worth considering before implementing:\n\n\n  The “workflow” feature used for the form requires a paid Slack plan.\n  The form’s fields don’t prefill the Jira form, and require copying from the description during ticket creation.\n\n\nConnecting Jira to Slack\n\nOnce connected, you will be able to make Jira tickets from any Slack message, as well as receive updates for new tickets, updated tickets, etc. Both Slack and Jira officially support connections to each other, so this process is straightforward.\n\n\n  \n    \n      Instructions\n      Image\n    \n  \n  \n    \n      Within your Jira project’s settings, navigate to the built-in “Slack integration” tab and click “Connect to Slack”.\n      \n    \n    \n      Provide Jira access to your workspace (this may require approval from your Slack administrator)\n      \n    \n    \n      Select the channel to integrate with. This is only used for optional new ticket notifications, so doesn’t matter much.\n      \n    \n    \n      The Jira bot should have posted in the connected channel. You now have the ability to create tickets from any message!\n      \n    \n  \n\n\nCreating a bug report form\n\nNext, we want a form that colleagues can fill in to give us any information we need. This can include simple things like a description of the bug, or a multiple choice dropdown asking the bug’s severity.\n\n\n  \n    \n      Instructions\n      Image\n    \n  \n  \n    \n      Open up the settings for the channel you want bugs to be reported in, then “Add a workflow” under “Integrations”.\n      \n    \n    \n      Give your workflow a simple name.\n      \n    \n    \n      Create your form. The actual fields you need will vary massively, but using your Jira ticket’s fields is the easiest place to start.\n      \n    \n    \n      For now, just send the form output to the channel. We’ll need to change this later.\n      \n    \n    \n      Here’s a summary of the simple bug reporting workflow we’ve just created.\n      \n    \n    \n      And here’s how it can be used, by clicking the “+” under the message box and selecting the workflow.\n      \n    \n  \n\n\nNow, whenever somebody fills in the form, a message is sent to the channel. Nice!\n\n\n\nTidying up\n\nIf you try using Jira’s create ticket functionality from the form results, you may notice something… not great. The output is all combined into one line, making it essentially unreadable even for short forms:\n\n\n\nTo fix this, we need to change our workflow. Instead of sending the form results directly into the channel, we are going to send a separate message, using the received values:\n\n\n  \n    \n      Instructions\n      Image\n    \n  \n  \n    \n      Open up your workflow’s settings, and click “Add step” at the bottom. We want to “Send message”.\n      \n    \n    \n      We now have to essentially recreate the previous message. All the variables are easy to access, including metadata such as who submitted the form.\n      \n    \n    \n      Our workflow now has an additional step. Don’t forget to disable the message sending in the “Open a form” step, or the results will be sent twice!\n      \n    \n  \n\n\nAll done! Anyone submitting the bug report form should now see the data posted in the Slack channel, where it can be triaged easily.\n\nPotential improvements\n\nWhilst this setup is an improvement over our former process (or no process!), it’s definitely not perfect. The obvious improvement would be converting the form directly into a JIRA ticket, but I’m not sure how to do that whilst also ensuring potential bugs are triaged / discussed first.\n\nBesides that, in the shorter term a couple of simple changes can make the process smoother:\n\n\n  In the Slack channel’s settings, you can change posting permissions so that only the workflow has permission to post.\n  The workflow’s icon can be customised via its settings.\n\n"
    } ,
  
    {
      "tags"     : "LastPass, Chrome, Security",
      "title"    : "Migrating from Chrome's Password Manager to LastPass, and tidying up 10+ years of password clutter",
      "excerpt"  : "I’ve been using Chrome since its 2008 release, and rely on the password manager daily. As you might expect, after 14 years I built up a lot of saved passwords (1000+)! However, migration to a proper solution is long overdue, here’s how I did it and tidied up my passwords at the same time.\n",
      "url"      : "/migrating-to-lastpass-and-tidying-up/",
      "date"     : "Nov 17, 2022",
      "content"  : "I’ve been using Chrome since its 2008 release, and rely on the password manager daily. As you might expect, after 14 years I built up a lot of saved passwords (1000+)! However, migration to a proper solution is long overdue, here’s how I did it and tidied up my passwords at the same time.\n\nBackstory\n\nConsidering how much of my life is online, and how security conscious I am, using Chrome’s Password Manager was always a guilty secret. I almost always use unique passwords, always use 2FA, and even use a unique email per service (so the source of any spam emails can be identified). However, a lot of sites still don’t support 2FA, so all it would take to compromise an unknown number of my accounts is one bit of malware. Uh oh.\n\nWhilst my Google account is secure, can I really be as confident in my personal machine / phone, both of which have access to all those passwords at any time? Probably not. As such, I decided it was time to finally migrate to a “proper” solution. I went for LastPass as it was very highly rated, easy to use, and supported all operating systems I work on. It might not be the cheapest, but $3 vs $5 per month really isn’t much for a comfortable password management experience!\n\nHowever, I need to get my 1000+ Chrome passwords over there…\n\nMigrating to LastPass\n\nInitial setup\n\nTo start with, I installed LastPass’ Chrome extension1 and Android app2. I generally used the default settings, and whilst I would have appreciated a little more guidance on which options were more secure, nothing was impossible to Google.\n\nImport &amp; export\n\nLuckily, LastPass is ready for Chrome’s password file format, so this process is very simple:\n\n\n  Go to Google Password Manager’s options.\n  Click “Export”, Chrome Passwords.csv will download.\n  Open LastPass → Advanced Options → Import → Chrome.\n  Upload the .csv.\n\n\nLastPass handles this pretty smoothly, even with 1000 passwords. I encountered a few “broken” passwords, where an Android app’s package name &amp; password had been transferred, but this isn’t LastPass’ fault!\n\nPost-import state\n\nNow all the passwords have been imported, we can use LastPass’ “Security score” to determine roughly how secure we are. 74.4% is pretty low, however I was pretty confident this was actually due to duplicated / bad data. So, the next step is tidying up the passwords into something more useful.\n\n\n  \n    \n      Password list\n      Security check\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nTidying up LastPass\n\nOrganising\n\nFirst, I wanted to group all my passwords by category. This way the list will become more manageable, easier to maintain, and I can clear out duplicates as I go.\n\nI went for the following fairly generic categories:\n\n\n  Android: Logins for apps, these are in a format unlike all other logins and were deleted later.\n  Financial: Banking, investment, property purchases, etc.\n  Gaming: Steam, Epic Games, various sites with unique logins.\n  Media: Videos, music, artwork, etc.\n  Online: Services that you “need” a login to when using the internet. Samsung, Google, Apple, etc.\n  Personal: Healthcare services, pet care services, piracy sites(!).\n  Shopping: Amazon, eBay, supermarkets, hardware, etc.\n  Social: Slack, Reddit, Twitter, etc.\n  Travel: All the hotel / airline / train accounts that end up being created during travelling.\n  Utility: Electricity, gas, water, phone, internet, etc.\n  Work: Anything “professional”. So domain management, programming resources, university, etc.\n\n\nGrouping these into categories took MUCH longer than it should have (multiple hours), due to LastPass’ somewhat unresponsive site. Luckily this is only a one-time process, as having to repeat this process regularly would be impossible!\n\n\n  \n    \n      Password list\n      Security check\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nTidying\n\nThe deletion of obviously outdated / irrelevant accounts in the previous step helped quite a lot, bumping the security score up to 82.1%! However, we can do much better than that…\n\nAgain I found myself fighting with LastPass’ interface a bit here. I wanted to view all logins with warnings, which was only accessible via the “Security Dashboard”. However, for each of these I then wanted to search my passwords (to find duplicates, a common issue). Opening 2 tabs of the extension didn’t work reliably, so I had to keep renavigating between the 2 screens! Very frustrating.\n\nLastPass has 3 categories of “bad” passwords:\n\n  Weak: Whilst I randomly generated the vast majority of my unique passwords, I had used a “throwaway” password for a few services I didn’t care about. Some of these have since become more important (e.g., Nintendo!), so I had ~20 passwords to actually change.\n  Missing: These were all accidental saves, so could be deleted safely.\n  Reused: These were mostly caused by services having multiple subdomains / domains over time that are used for logging in. For each of these, the duplicates could be safely removed once I worked out the current URL.\n\n\n\n  \n    \n      Password list\n      Security check\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nSecuring\n\nAfter clearing up all the flagged passwords, I ended up at 97.6%. Why not higher? Well, some passwords had 50% / 75% strength. This isn’t low enough to be flagged as weak, but still affects the score! Fixing these few didn’t taking long, ending up on 98%:\n\n\n\nWhy not 100%? Well, on the web it’s tricky to find out. Luckily, the mobile app provides a more detailed breakdown:\n\n\n\nAh, so 1% is due to accessing LastPass from mobile(?), and 1% is because I initially had offline access turned on. The documentation is a little unclear on what precisely deducts these final few points, but it looks like 98% is the highest I can go.\n\nIt’s a shame 100% doesn’t appear possible, but it’ll have to do! Especially as “the security challenge is just a tool and aiming for a 100% score isn’t totally necessary”3.\n\nFinal steps\n\nTo finish up my migration, I took the scary step of deleting all my saved Chrome passwords! This can be done in “Privacy and security” → “Clear browsing data” → “Advanced”, and make sure “Passwords and other sign-in data” is selected, along with the “All time” time frame.\n\nNext, I made sure to properly delete the .csv file used for the import, since that file has all the passwords without any protection! Finally, in Chrome I turned off autofill prompts under the “Auto-fill” tab.\n\nFinally, my passwords actually feel secure for the first time!\n\nReferences\n\n  \n    \n      https://chrome.google.com/webstore/detail/lastpass-free-password-ma/hdokiejnpimakedhajhdlcegeplioahd &#8617;\n    \n    \n      https://play.google.com/store/apps/details?id=com.lastpass.lpandroid &#8617;\n    \n    \n      https://community.logmein.com/t5/LastPass-Support-Discussions/Lastpass-Security-Score-of-100/m-p/255418/highlight/true#M24981 &#8617;\n    \n  \n\n"
    } ,
  
    {
      "tags"     : "Review, Bugs",
      "title"    : "How minor bugs and security flaws can erode user trust: Examining my unfortunate experience with Bloggie.io",
      "excerpt"  : "Whilst wandering through GitHub recently, I discovered the Tokyo-based Bloggie.io, a markdown  blogging platform that gave a great first impression. Unfortunately, after an hour or so of clicking around, I realised my enthusiasm and trust had completely eroded. But why &amp; how?\n",
      "url"      : "/how-bugs-erode-user-trust-with-bloggie-io/",
      "date"     : "Nov 15, 2022",
      "content"  : "Whilst wandering through GitHub recently, I discovered the Tokyo-based Bloggie.io, a markdown  blogging platform that gave a great first impression. Unfortunately, after an hour or so of clicking around, I realised my enthusiasm and trust had completely eroded. But why &amp; how?\n\nBefore I get too into the article, I want to clarify that I do genuinely like the idea behind Bloggie.io, despite how this post might come across! However, it is a great personal example of how user trust erodes a little with each minor bug, a principle with relevance to all software engineering / product teams.\n\nHow I discovered Bloggie.io\n\nSo, how did I first find Bloggie.io? Google? A friend’s post? Nope, GitHub stalking!\n\nI was looking at the first GitHub issue I ever created1 way back in 2016; a UI issue with a “guided tour” library I was using in a game. I also raised a PR2 fixing it a year later and… it got no attention.\n\nNot an ideal first experience on GitHub! Out of sheer curiosity I wondered what else the library’s author had created, and discovered they were part of an organisation: Bloggie.io. This described itself as “A blogging platform crafted for software developers”, which sounded intriguing and relevant… so I gave it a go.\n\nThe good start\n\nFirst impressions\nThe initial impression was very, very strong. I liked the focussed scope of the articles, how my desired topic (Android) was available in a single click from the homepage, and the clean and simple design.\n\nI’m always interested in who is behind hobby projects, and Bloggie.io’s “Our Team” page3 is very endearing. I genuinely like reading about the professional &amp; personal interests (&amp; gifs when mousing over photos…) of small project maintainers, especially when it’s only by 3 people! A snippet of the overall description helped set the scene too:\n\n\n  We enjoy working on it, we enjoy learning from the experience, we enjoy the collaboration with each other.\n\n  We hope our perseverance and passion can turn into something valuable for you and the developers community.\n\n\nWhilst different demographics and individuals have their own preferences (obviously!), Bloggie.io’s simple, content-first, and to-the-point design is what I almost always look for. Additionally, it seemed to only want me to read and enjoy articles, whilst similar sites (e.g., Medium) push sign-ups very heavily. Luckily, Bloggie.io is fairly open about its inspiration from Medium (side by side comparison in a bit), from the overall design to the privacy policy4, which is:\n\n  a derivative of Medium Privacy Policy by Medium, used under CC BY-SA 2.0.\n\n\nBloggie.io vs Medium\n\nA brief side by side comparison should show the very similar, but simpler design Bloggie.io opts for:\n\n\n  \n    \n       \n      Medium\n      Bloggie.io\n    \n  \n  \n    \n      Homepage\n      \n      \n    \n    \n      Article\n      \n      \n    \n    \n      Category / Community\n      \n      \n    \n  \n\n\nSigning up\nSigning up was also very smooth, with GitHub (my preference!) and Twitter options. The lack of any manual signup was an unusual choice, but at least it prevents spam signups.\n\nI started a test post, and got thrown into a Markdown editor. No problem, I’m fluent in Markdown. I assumed the “Aa” button in the top right was some basic text styling (e.g., bold, italic) for those with less markdown experience. Nope, it says “Capitalise” in the hover text and when clicked… does nothing. A bit unexpected, but not a blocker.\n\nNext I spent a couple of minutes playing with the editor and writing my test post, then went to publish.\n\nPosting\nThis part of the experience had a few nice surprises, primarily the ability to share a draft version of your post with someone. I often wish I had this feature myself, and currently end up just showing people the GitHub version of a post, which sometimes have minor formatting issues in comparison to the final version. Very cool.\n\nUnfortunately, here’s where the first tiny potential security issue made itself clear to me. I noticed my post editing URL contained /705/. And if I started a new post, it was /706/. Uh oh, I now know the site likely has around 700 combined posts and drafts. Not necessarily an issue, but not information I needed to know. Publishing the post went smoothly.\n\n\n\nBloggie.io also has a “Notes” features, essentially the same as GitHub’s Gists. This uses a totally different editor to posts, with the preview being in a separate tab instead of side by side. The published note page is similar to the post page (minus author information &amp; comments), but here they use a GUID in the URL instead!\n\nIn a digital version of confirmation bias, the small URL decision for posts made the crucial change to my Bloggie.io exploration. Instead of being “I wonder if I can use this interesting platform”, it became “I wonder how many bugs I can find on here”, and by that stage anything less than a perfect site is doomed.\n\nAlas, Bloggie.io is not perfect.\n\nThe warning signs\n\nSo far, I have only found an unnecessary button that doesn’t work, and unusual decisions for URLs and signup options. These are all easily overlooked.\n\nLive editor\nSince I was starting to look for bugs, I opened up the demo editor. It invited me to “Try editing this area”, and after doing as instructed… the preview didn’t change. Considering the live editor worked whilst writing a post and the overall experience had been pretty smooth, I didn’t expect to face issues so soon!\n\n\n\nAfter trying to give it a helping hand by disabling adblock, clicking the preview, and refreshing the page, I had to conclude it’s just broken. Oops.\n\nOverlapping menus\nNext I looked at my example post, and realised the post “Share” and “Options” pop-up menus went underneath the very pretty code block, making them unreadable. Again, oops.\n\n\n\nAlright, so we’ve got some minor UI issues. And a bit of broken functionality here and there. Unfortunately, there’s more to come…\n\nThe cracks widening\n\nMaximum lengths\nAt this point I decided to see what non-destructive mischief I could get up to in the account page. First up, what’s the maximum name / description length? Well, it appears to be pretty much infinite. Setting a long name and bio also breaks the “Updated!” dialog at the top.\n\n\n\nUnlimited “claps”\nJust like Medium, Bloggie.io has a “Claps” feature that are essentially a “like” button. Unfortunately, it has a very obvious bug that occurs when clapping whilst logged out:\n\n\n  Click the “clap” button.\n  Click it again to “unclap”.\n  Repeat this as many times as you like.\n  Refresh the page, the article will have all the “claps”, but none of the “unclaps”!\n\n\n\n\nAt this point, the number and variety of bugs has ruled out the platform for me. If I’ve found 4-5 bugs in my first 10-15 minutes, I sadly can’t trust that any posts I make will be safe from deletion / corruption in the future.\n\nRules of engagement\nI also made the conscious decision at this point to not do any “advanced” bug finding. For example, no SQL injection, no header manipulation, I will only do simple things that any user could do without any technical knowledge. I decided to do this as performing actual attacks, proof of concept or not, against an unwilling hobby project just isn’t fair.\n\nGlobally unique titles\nNext, I suspected post slugs (the bit that identifies a post) weren’t being handled properly. To test this, I tried to publish a test post with the same name as an existing post (e.g., “An example post”). Since this is my only post with this name, it should be fine, but it looks like Bloggie.io only allows 1 post per slug across all users. Trying to publish a post with the same name as an existing one gives an unhelpful error:\n\n\n\nThe abyss\n\nUnfortunately here’s where I found some very concerning things.\n\nBreaking any post\n\nI discovered that it was possible to break any post on the site by creating a draft post with the same title. The incorrect “does this post exist” check above only applies on publishing, meaning it is trivial to break anyone’s posts:\n\n\n  A popular post with URL bloggie.io/@exampleuser/my-example-post exists.\n  I create a draft post called “My example post”. Publishing it won’t work, but that’s OK.\n  When the above URL is clicked, the site presumably gets the most recent post (mine!) with that slug.\n  As my post is a draft, other users can’t view it, so nothing happens.\n  As easily as that, the popular post cannot be accessed (even directly).\n\n\nUsername\nHow’s the username (used in URLs) filtering?\n\nWords\nWell, after trying admin, web, bloggie, and an unpleasant word or two, I’m pretty confident there’s no filter in place.\n\nSymbols\nOkay, but the words are still alphanumeric. What about @, ?, or even my beloved zero width space ​? Uh oh, they all work (although are URL encoded in the URL).\n\nImpersonation\nSurely having a weird username is just a fun bug, right? Unfortunately not. Using zero width spaces in your name, you can now impersonate any user easily.\n\nFor example, to impersonate a user at https://bloggie.io/@Jake I would put the space before my name, ending up with https://bloggie.io/@​Jake. They look identical until you click, then the character gets URL encoded.\n\nMadness\nUsing symbols to impersonate any user almost undetectably is a good start. What else can we have as our username?\n\n\n\n… Oh. There really are no limits!\n\nAvatar\nIf you were going to build an avatar picker, what would your initial ideas for restrictions be? File type, file size, things like that? Well, none of those here!\n\nTo test this, I tried selecting a 1 GB zip file. It happily tried to upload it as a binary in a multipart form data, I closed the tab after ~10 seconds, in case I broke anything on the server. When trying a smaller non-image file, I got sent to an error page. Again, hopefully this didn’t break anything.\n\n\n\nConclusion\n\nSo, after all those issues, surely the site is not worth anyone’s time, right?\n\nThe opposite! Despite these many fairly small issues, the core idea and functionality is solid. If I didn’t have my own sites already, or had limited web hosting knowledge, I would love a place to easily self-host a Markdown blog. This appeal increases massively when Bloggie.io appears to essentially be Medium without all the advertising / anti-consumer practices5! It helps to have a catchy name too, right?\n\nGiven a bit of tidying, and a bit more work growing the user base (all “Latest” posts in 2022 are from 2 authors, the owners), there is massive potential. Many software developers like writing about their experience, are comfortable with Markdown, and don’t seek any financial benefit: Bloggie.io would suit this.\n\n10 potential improvements\n\nFinally, here’s a short list of things that I think could really help Bloggie.io grow and succeed. I wish it the best of luck!\n\n\n  Fix the bugs / issues raised in this post, obviously!\n  Figure out how to grow the number of authors. Without content to discover, there’s no reason to stick around.\n  Adding the ability to export all posts, in case a user wants to migrate to another platform.\n  Open sourcing if possible, to allow users to fix bugs.\n  More structured categories (e.g., “Web Dev” should include “JavaScript”).\n  More accurate search: currently “Jake” returns 20 results, none of which contain “Jake”!\n  Add ability to signup without a Twitter or GitHub account, or at least add the ability to hide this connection on a user’s profile.\n  Add ability to customise posts shown on homepage (similar to StackOverflow).\n  Add dark mode.\n  Add related posts (not just other author posts) at the end of an article.\n\n\nReferences\n\n  \n    \n      https://github.com/worker8/TourGuide/issues/88 &#8617;\n    \n    \n      https://github.com/worker8/TourGuide/pull/110 &#8617;\n    \n    \n      https://bloggie.io/team &#8617;\n    \n    \n      https://bloggie.io/privacy &#8617;\n    \n    \n      https://news.ycombinator.com/item?id=24942037 &#8617;\n    \n  \n\n"
    } ,
  
    {
      "tags"     : "Google Analytics, Jekyll",
      "title"    : "How to migrate a Jekyll Minima blog from Universal Analytics to Google Analytics 4 (UA to GA4)",
      "excerpt"  : "When I first set up my Jekyll blog with Minima, it had built-in support for Google Analytics. Great! However, only using a legacy “Universal Analytics” ID seemed to work. This was fine for a few years, until I discovered the system is being sunset, and all users need to move to Google Analytics 4 ASAP… Here’s how to do it.\n",
      "url"      : "/migrating-jekyll-minima-from-ua-to-ga4/",
      "date"     : "Nov 14, 2022",
      "content"  : "When I first set up my Jekyll blog with Minima, it had built-in support for Google Analytics. Great! However, only using a legacy “Universal Analytics” ID seemed to work. This was fine for a few years, until I discovered the system is being sunset, and all users need to move to Google Analytics 4 ASAP… Here’s how to do it.\n\nOn the 10th November I received the following email from Google, prompting me to actually fix this long-ignored issue:\n\n\n  We’ll soon sunset Universal Analytics\n\n  On 1 July 2023, Universal Analytics will stop processing new hits. If you still rely on Universal Analytics, we urge you to prepare for the future by moving over to Google Analytics 4, our next-generation measurement solution.\n\n\nI only use the very basic Google Analytics features (which pages are viewed, how often), and as such the migration was pretty simple.\n\nSummary\n\nBefore I run through each step in detail, here’s the high level overview of how to migrate from UA to GA4:\n\n\n  Create a new GA4 property in Google Analytics to get a GA4 ID.\n  Override your Jekyll blog’s UA code to support GA4.\n  Tidy up how your GA4 ID is used.\n  Testing.\n\n\nStep 1: Setting up GA4\n\nStep by step\n\n\n  \n    \n      Step\n      Screenshot\n    \n  \n  \n    \n      Visit your existing Universal Analytics page, and click the “Let’s go” button in the warning banner.\n      \n    \n    \n      On the setup assistant page, click “Get Started” to begin creating a GA4 property.\n      \n    \n    \n      Click “Create and continue” on the pop-up with more information about what we’re about to do.\n      \n    \n    \n      I didn’t have any existing tags, so I selected “Install a Google tag” and clicked “Next”.\n      \n    \n    \n      Finally, I opened the “Install manually” tab and saw both my GA4 tag (G-99...) and the HTML I need to embed.\n      \n    \n  \n\n\nOnce you’ve got your bunch of HTML, copy it somewhere safe, we’ll need it in Step 2. I’ve included sample code below with Step 3 of this article already done.\n\nGoogle tag code\n\n&lt;!-- Google tag (gtag.js) --&gt;\n&lt;script async src=\"https://www.googletagmanager.com/gtag/js?id={{ site.google_analytics }}\"&gt;&lt;/script&gt;\n&lt;script&gt;\n  window.dataLayer = window.dataLayer || [];\n  function gtag(){dataLayer.push(arguments);}\n  gtag('js', new Date());\n\n  gtag('config', '{{ site.google_analytics }}');\n&lt;/script&gt;\n\n\nStep 2: Replace existing tracking\n\nNow that we have our new GA4 HTML, we need to replace what is currently on our site. This is done by overriding the included google-analytics.html file.\n\n\n  Inside your Jekyll blog’s base folder (e.g., where _posts is), create _includes.\n  Find your Minima theme’s _includes folder, commonly found at:\n    \n      Windows: C:\\Ruby27-x64\\lib\\ruby\\gems\\2.7.0\\gems\\minima-2.5.1\\_includes\n      Mac: /usr/local/lib/ruby/gems/2.6/gems/minima-2.5.1/_includes\n    \n  \n  Copy the google-analytics.html file from the Minima _includes folder into your site’s _includes folder.\n  Your site is now using GA4!\n\n\nWhilst you could finish the process here, it’s worth doing a little additional tidying up.\n\nStep 3: Tidy up ID usage\n\nBefore we replaced our Google Analytics file, the tracking ID came from the _config.yml page. Let’s make that happen again.\n\n\n  Replace the old ID in _config.yml with your new ID.\n  Replace both instances of the new ID in google-analytics.html with G-99X0QYL39T.\n\n\nNow, the ID will be pulled from our config, just as it was previously. Here is my commit performing these changes on my personal blog.\n\nStep 4: Testing\n\nThere’s a few ways to test your implementation, but by far the easiest is just running your site locally and checking event sending works.\n\nBy default, no tracking happens unless the site is running in production. We’ll want to disable that temporarily by overriding the head.html file (just like we did with google-analytics.html):\n\n  Again, copy head.html from Minima’s files to your blog’s files.\n  Edit it, removing jekyll.environment == 'production' and .\n  Save.\n\n\nRunning your site locally should now be pointing correctly at your new GA4 property. Looking at the dev console’s (F12, or Ctrl/Cmd + Shift + I) “Network” tab whilst a page is loading should show the Google Analytics script being fetched (with your ID), and then a “ping” being responded to with a 204:\n\n\n\nAfter a short wait (took 60 minutes for me, can take up to 24 hours) you should also see your page view on your new GA4 property’s dashboard.\n\nAssuming both of these tests are successful, you’re all done! Don’t forget to undo your changes to head.html before you push your code changes, and enjoy all the new features GA4 has to offer.\n"
    } ,
  
    {
      "tags"     : "gitStream, GitHub",
      "title"    : "Using gitStream for 'Continuous Merge': automatically approving safe PRs, assigning reviewers, estimating review time, and more",
      "excerpt"  : "gitStream is a GitHub app that aims to improve the PR review process, a common bottleneck during development. It aims to extend CI/CD to include CM: Continuous Merge. In this post, I’ll explain what it is, how it works, and what it can be used for.\n",
      "url"      : "/using-gitstream-to-improve-pr-workflow/",
      "date"     : "Nov 7, 2022",
      "content"  : "gitStream is a GitHub app that aims to improve the PR review process, a common bottleneck during development. It aims to extend CI/CD to include CM: Continuous Merge. In this post, I’ll explain what it is, how it works, and what it can be used for.\n\nWhat can it do?\nPretty much anything on a PR involving labelling, adding reviewers, or autoapproving based on criteria. The examples page lists some great starting points most projects could benefit from. Some basic capabilities are showcased in my example repository, such as review time labels and auto approvals.\n\nThere is a blog post by the creators (and a podcast) about the reason behind gitStream’s creation and what it aims to solve that is definitely worth a read. Unlimited usage of gitStream is provided free by LinearB, presumably as a loss-leader for their paid “WorkerB” Chrome extension1 and “LinearB” workflow automation / analytics solution2.\n\nReviewers\nSpecific individuals (or groups) can be assigned as reviewers based on PR characteristics, such as lines / files of code changed or filetype3. Additionally, the number of approvals required can be adjusted dynamically, such as making PRs with server config changes requiring more approvals than those updating documentation4.\n\nLabels\nAdding labels based on the content of a PR doesn’t seem very powerful initially, but it has a lot of potential! GitHub’s PR overview screen doesn’t show many details about the contents of a PR, so even something as simple as colour-coded labels based on estimated review time could help smaller PRs get approved quicker5.\n\nApproving PRs\nWhen working on a project with experienced engineers, there’ll likely be a few PRs that realistically don’t need human eyes. This could be test updating, documentation updating, or some project-specific metadata that needs frequent changes (e.g., release notes). Luckily, gitStream lets you set criteria under which a PR should be autoapproved or even merged, avoiding the situation where a small typo fix takes days to be deployed.\n\nGood starting criteria could be if a PR only contains documentation6, or if the PR only adds new tests7.\n\nEnforcing arbitrary rules\nWhilst most languages / developer environments have their own ways of indicating deprecated functionality (e.g. an annotation), this can also be performed platform agnostically inside gitStream. For example, if multiple projects are slowly migrating from oldapi.example.com to newapi.example.com, regular expression searches could be used to add warnings to any code additions featuring the deprecated URL8.\n\nMultiple actions\nWhilst these individual actions are already useful by themselves, the true value comes when they are used with each other, making lots of little optimisations to the PR workflow.\n\nUsing this PR featuring only small changes to a markdown file as an example, it has been autoapproved with a 1-minute review estimate and a safe-changes label. On a busy team, these clear indicators of an easily mergeable PR will help it progress quickly, whilst reducing the cognitive load added by a long list of pending PRs.\n\nAdditional functionality\nAlong with these basic implementations, the documentation contains a detailed list of data manipulation tools and actions that can be combined and utilised. I’ll briefly summarise these below, to give an idea of possibilities.\n\nData manipulation (docs)\n\nBasic logical operators (every, includes, filter, match etc) are useless by themselves, but provide a solid framework to build complex logic on.\n\nThe overall contents of a PR can be checked using:\n\n\n  allDocs: Are all files .md, .mkdown, .txt, or .rst.\n  allImages: Are all files .svg, .png, or .gif.\n  allTests: Do all files have test or spec in the filename / path.\n\n\nWhilst additional data can also be extracted using:\n\n\n  estimatedReviewTime: Estimated review time, in minutes.\n  extensions: A list of all unique file extensions.\n  isFormattingChange: For JavaScript, TypeScript, JSON, YAML, or HTML files, check all changes are only formatting.\n  matchDiffLines: Used to check the contents of every changed line according to a regular expression.\n\n\nActions (docs)\n\nAll of the actions are self explanatory, and contain basic customisation (e.g. label text). Currently, the actions available are add-comment, add-label, add-reviewers, approve, merge, set-required-approvals, require-reviewers, request-changes, and finally update-check (to override a check’s outcome).\n\nWhat’s the setup process?\n\nThe official documentation contains straightforward instructions, with the core steps being:\n\n\n  Add gitStream to your account / organisation, and give it access to the target repository.\n  Add the basic framework file to your project’s GitHub workflow (.github/workflows/gitstream.yml) to let gitStream run &amp; access what it requires.\n  Add a configuration file with the specific automations required (.cm/gitstream.cm).\n  Create a temporary PR, so that gitStream is triggered. You should see it running as a GitHub Action.\n  (Optional) Set gitStream as a required check on your main branch.\n\n\nWhat are the limitations?\n\nLack of extendability\n\nWhilst the small collection of low level functions are useful for creating more complex logic, they are just a start. Currently I don’t believe there is any way to create more advanced functions and reuse them, or expand much on the built-in filters. This functionality is “coming soon”9, and would help gitStream achieve wider adoption.\n\nClosed source\n\nConsidering gitStream’s trusted access to all source code in a repository in real-time, it would be beneficial to know what it is actually doing. This is doubly so for an application that requires the ability to add and merge code10. Whilst the FAQ states “the source code is being scanned in the repo and is not shared with any external services”, it does not seem possible to actually validate this.\n\nBesides security concerns, there is the everyday annoyance of being unsure how the high level filter functions work. For example, estimatedReviewTime contains no information as to how it calculates the result, and as such the accuracy is unknowable11:\n\n  Returns the estimated review time in minutes based on statistical model. The model uses the PR size and type of file changed to produce the estimation.\n\n\nNo community\n\nWhilst gitStream has a lot of helpful functionality, it seems to have very little traction in the developer community yet. As such, there are not many (read: none) “out of the box” configuration files that can be copied. Instead, any advanced functionality desired would require writing from scratch. In fact, Googling “gitstream” returns several projects, with the correct one only featuring in around half the results.\n\nWhilst this is likely due to the very recent nature of gitStream (it appears to only be a few weeks old), the lack of any customer forums or StackOverflow questions suggests the only source for assistance will be from the application developer.\n\nConclusion\n\nOverall, gitStream appears to have immense potential as a platform for building on. Similar to GitHub Pages and GitHub Actions, it provides a seemingly obvious yet currently lacking function. The “continuous merge” phrase is catchy, and has a chance of catching on. I have no doubt that if the phrase and the application are marketed and advocated well, they could become commonplace.\n\nWhilst I would recommend gitStream on open source projects, currently I’m undecided on whether I would advocate it on my company’s commercial, closed-source projects. There are a few changes that would convince me to use it, although I’m of course aware they may not be possible:\n\n\n  Open sourcing where possible: Currently it is hard to trust the application, especially whilst it still has a small userbase.\n  Providing many more examples: Whilst the current examples page is a good start, and lets developers add the basics, a collection of 10-20 more advanced implementations would be very beneficial.\n  Smoother onboarding process: The current setup process requires 5 steps. Ideally it would be possible to grant the application access to a repository, then it could raise a PR configuring itself. There could be a “do manually, with minimum permissions” options, and a “do automatically, with config editing permissions” install option.\n  More built-in functions: Whilst the initial function offerings are a good start, the lack of ability to customise allTests’s logic or add new functions makes working with them hard.\n\n\nReferences\n\n\n  \n    \n      https://linearb.io/dev/workerb-for-chrome-onboarding/ &#8617;\n    \n    \n      https://linearb.io/ &#8617;\n    \n    \n      https://docs.gitstream.cm/examples/#assign-reviewers-by-type-of-change &#8617;\n    \n    \n      https://docs.gitstream.cm/examples/#more-approvals-for-complex-changes &#8617;\n    \n    \n      https://docs.gitstream.cm/examples/#label-prs-by-their-complexity &#8617;\n    \n    \n      https://docs.gitstream.cm/examples/#approve-safe-changes &#8617;\n    \n    \n      https://docs.gitstream.cm/examples/#approve-safe-changes &#8617;\n    \n    \n      https://docs.gitstream.cm/examples/#request-changes-on-deprecated-apis &#8617;\n    \n    \n      https://docs.gitstream.cm/faq/#custom-filter-functions &#8617;\n    \n    \n      https://docs.gitstream.cm/faq/#why-does-gitstream-require-permission-to-write-code &#8617;\n    \n    \n      https://docs.gitstream.cm/filter-functions/#estimatedreviewtime &#8617;\n    \n  \n\n"
    } ,
  
    {
      "tags"     : "Google Sheets, Analysis",
      "title"    : "6 useful Google Sheets analysis formulas and techniques from my Twitch data analysis",
      "excerpt"  : "I recently published a guide to analysing your Twitch data, from streamers watched to emotes used. This involved a lot of amazingly complicated Google Sheets formulas, enough to warrant a separate write-up. There are 6 extremely helpful formulas if you’re in a similar scenario, and should be somewhat interesting if not!\n",
      "url"      : "/6-useful-google-sheets-techniques/",
      "date"     : "Nov 1, 2022",
      "content"  : "I recently published a guide to analysing your Twitch data, from streamers watched to emotes used. This involved a lot of amazingly complicated Google Sheets formulas, enough to warrant a separate write-up. There are 6 extremely helpful formulas if you’re in a similar scenario, and should be somewhat interesting if not!\n\nFor reference, here is the spreadsheet all of these formulas are used in.\n\nDynamic row contents, with data lookup\nThe 3 columns in “Streamers watched” &amp; “Players used” (title, count, minutes) are actually totally independent, with the main challenge coming from the dynamic data (e.g. streamer names) that might be there. I discovered =SORT(UNIQUE(Minutes!D2:D)) is an easy way to get an alphabetised list of all unique values in a range.\n\nThe “Count” column just counts the number of rows in the watch data features this player / streamer, e.g. COUNTIF(Minutes!$D$2:$D, E5). The “Minutes” column works the same, just with SUMIF.\n\nOne sneaky trick to avoid lots of 0s in the empty rows is some conditional formatting to set the text colour to white if the value is 0, which looks like an empty cell!\n\nLargest values in a range\n“Longest sessions” uses a technique I haven’t used before. By using LARGE we can get the top X value for a range, then find that value again, and fetch another cell in the row (using INDEX and MATCH). This might seem a convoluted way to fetch a top value but… that’s Google Sheets.\n\nFiltering rows by timestamps\n“Streams by year” was my first time messing around with dates in Google Sheets. All we need to do is use COUNTIF to count the rows whose timestamp meets both criteria: After or on the 1st Jan in the target year, and before 1st Jan the next year. This is combined with the count / sum logic from the player / streamer section to get totals.\n\nAdding all numbers within text cells in a range\nHere’s where the crazy formulas start! Getting the number of cheers messages was easy, just filter the sheet’s rows by type. The total bits donated were a bit trickier: my initial approach1 was finding all CheerX and adding them. This took a long time to get working, and I then realised you can send bits using words other than Cheer (e.g. ShowLove100). Oops!\n\nMy second approach was to just pull out all numbers in “Cheer” messages, and add them together. This has the potential to miscalculate (e.g. “Cheer100 10/10 stream” would count as 120 (100 + 10 + 10)), but it seems pretty accurate. However, this formula is a wild one:\n\n  At the outer layer, we’re using some completely baffling SUM and SPLIT logic to pull out all numerical values and add them together2. However, this only works for a single cell…\n  Putting a range into this formula works, we just need to dynamically define where the “cheer” rows appear in our Events. We need to do this twice, as the range appears twice in the formula.\n  To get our starting point, we need to count the number of “chat” rows, then add 2: COUNTIF(Events!$A$2:$A, \"chat\") + 2). This will be the first “cheer” row.\n  To get our finishing point, we need to use the same “chat” row count, and add the number of “cheer” rows (plus 1 due to zero indexing). So far, so good.\n  Now the awkward bit. To combine these 2 into a range (e.g. G100:G120), we need to use INDIRECT (to let us work with the cell reference as a string), and CONCATENATE (to combine our starting and ending point into a range).\n\n\nHere’s how the process of building this formula looked, I hope this makes sense if I try to reuse it in a few months!\n// Sum all numbers in a cell\n=SUM(SPLIT(A1,CONCATENATE(SPLIT(A1,\".0123456789\"))))\n\n// Sum all numbers in range\n=SUM(SPLIT(A1:A10,CONCATENATE(SPLIT(A1:A10,\".0123456789\"))))\n\n// Sum all numbers in range, with dynamic starting &amp; ending point\n=SUM(SPLIT(A&lt;start point&gt;:A&lt;end point&gt;,CONCATENATE(SPLIT(A&lt;start point&gt;:A&lt;end point&gt;,\".0123456789\"))))\n\n// Sum all numbers in range, with dynamic starting &amp; ending point, and string mangling\n=SUM(SPLIT(CONCATENATE(INDIRECT(\"A\" &amp; &lt;start point&gt; &amp; \":A\" &amp; &lt;end point&gt;)),CONCATENATE(SPLIT(CONCATENATE(INDIRECT(\"A\" &amp; &lt;start point&gt; &amp; \":A\" &amp; &lt;end point&gt;)),\".0123456789\"))))\n\n// Sum all numbers in range, with dynamic starting &amp; ending point, and string mangling, and real start / end points, and full cell references\n=SUM(SPLIT(CONCATENATE(INDIRECT(\"Events!G\" &amp; (COUNTIF(Events!$A$2:$A, \"chat\") + 2) &amp; \":G\" &amp; (COUNTIF(Events!$A$2:$A, \"chat\") + COUNTIF(Events!$A$2:$A, \"cheer\") + 1))),CONCATENATE(SPLIT(CONCATENATE(INDIRECT(\"Events!G\" &amp; (COUNTIF(Events!$A$2:$A, \"chat\") + 2) &amp; \":G\" &amp; (COUNTIF(Events!$A$2:$A, \"chat\") + COUNTIF(Events!$A$2:$A, \"cheer\") + 1))),\".0123456789\"))))\n\n\nCounting occurrences of characters in range\nTo get the total chat messages (B40), I had to combine 2 bits of data:\n\n  The total rows in “Events” that are chats or cheers:\n    COUNTIF(Events!A2:A, \"chat\") + COUNTIF(Events!A2:A, \"cheers\")\n    \n  \n  The number of times ; appears in these rows, as the raw data uses this when multiple messages are sent in a session. The number of these present are counted via some borderline magic using ArrayFormula and SUBSTITUTE:3\n    ArrayFormula(SUM(LEN(Events!G2:G))-SUM(LEN(SUBSTITUTE(Events!G2:G,\";\",\"\"))))\n    \n  \n\n\nCounting characters in a filtered range\nInterestingly, chat characters required a totally different approach to chat messages. It’s also a formula I built entirely myself, whereas the rest are mostly other people’s work stuck together!\n\nWe can use our same dynamic range calculating &amp; string mangling logic from “Cheers totals”, to give us our target range (all chat &amp; cheer messages):\n=INDIRECT(\"Events!G2:G\" &amp; (COUNTIF(Events!A2:A, \"chat\") + COUNTIF(Events!A2:A, \"cheer\") + 1))\n\n\nThis gives an array containing every chat or cheer message. We can then use ArrayFormula(LEN(...)) to convert this array of cells into an array of the character count in each cell. Finally, SUM(...)ing these give us… the total characters in all the filtered cells:\n\n=SUM(ArrayFormula(LEN(INDIRECT(\"Events!G2:G\" &amp; (COUNTIF(Events!A2:A, \"chat\") + COUNTIF(Events!A2:A, \"cheer\") + 1)))))\n\n\nReferences\n\n  \n    \n      https://stackoverflow.com/q/74103189/608312 &#8617;\n    \n    \n      https://webapps.stackexchange.com/a/65988/140439 &#8617;\n    \n    \n      https://www.ablebits.com/office-addins-blog/google-sheets-character-word-count/ &#8617;\n    \n  \n\n"
    } ,
  
    {
      "tags"     : "Web, JavaScript",
      "title"    : "How to count the number of pixels per colour in an image, without installing any software",
      "excerpt"  : "Whilst working on a new project recently, I needed a list of all hex codes used in a very large pixel art image (1,000,000 pixels), sorted by how many pixels had each colour. I struggled to find any simple solution, so here’s how I did it!\n",
      "url"      : "/counting-pixel-colours-in-an-image/",
      "date"     : "Sep 23, 2022",
      "content"  : "Whilst working on a new project recently, I needed a list of all hex codes used in a very large pixel art image (1,000,000 pixels), sorted by how many pixels had each colour. I struggled to find any simple solution, so here’s how I did it!\n\nAn important caveat is that I’m very aware I could have downloaded various libraries / image editors to solve this but… maybe I don’t want to! This solution just needs Chrome, and access to dev tools.\n\nPhotoshop’s limitations\n\nMy initial instinct was to open the image in Photoshop, and use the Histogram feature to get my data. I used this for my LEGO lenticular mosaic in 2017, so maybe that’ll work…\n\n\n\nWell, that’s something. Not what I wanted, but something. We can see the colours tend to spike at either end of the chart, suggesting white and black, as well as pure-colour pixels are common. However, with 250+ colours in my image, this isn’t good enough.\n\nGetting all colours\n\nAfter many fruitless Google searches for “online image processing”, “pixel colour counter”, “online count pixels” etc, I finally found a site that seemed like what I wanted.\n\nAshley Grenon’s Pixel Color Counter is a no-frills site that, unsurprisingly, counts how many pixels of each colour there are. It’s also open source. Let’s use a cute pixel art Charmander to test it out:\n\n\n\nOkay! We’ve got 7 unique colours, and how many pixels each colour occupies. For this example, we could just look at the image in Photoshop or similar to find our hex codes, but what if we have a more complex image? Let’s try pixel art of the first 9 pokémon, to keep with the theme:\n\n\n\nAlright, 36 is too many colours to look each up, there must be a better way.\n\nCatching the raw data\n\nSince we know Pixel Color Counter is a simple JavaScript webapp, we can look directly at the colour data after it’s been processed! If you’ve not used Chrome’s dev console before this might be a little bit confusing, but it’s easier than it looks:\n\n\n  Open the console: Press F12, or Ctrl + Shift + I, or Options -&gt; More tools -&gt; Developer tools.\n  Find our target code: Use the “Sources” tab at the top, and open counter.js under /assets/.\n  Set a breakpoint: Click the number “33” next to return colorCounts, this will make the code pause next time we’re about to return the colour data.\n\n\nYour console should look like this:\n\n\n\nFinally, upload an image, and your breakpoint should be hit! Notice colorCounts, full of lots of RGBA values? That’s what we were after.\n\n\n\nInspecting the raw data\n\nIf we switch to the “Console” tab, type colorCounts, and press enter, we can see what our captured data looks like.\n\n\n\nHere’s where we get our first red flag. The data looks OK at first glance, but eventually you may notice the data’s keys (e.g. each colour) are named as the CSS code required to display them on screen. This works fine if we only ever want to show these colours on the website, but we want to extract all the data, preferably as standard hex codes!\n\nConverting the raw data\n\nSo, what do we do? Well, we write a script to sort the data out for us. Knowing what the following code does isn’t at all necessary to use it.\n\n\n  Make sure your breakpoint from earlier has been hit.\n  Copy and paste the following into the “Console” tab\n  Press enter, and the result will be a tidied, sorted array!\n\n\n// Prepare a new empty array, to store our tidied up data in.\nvar newArray = []; \n\nObject.keys(colorCounts).forEach(key =&gt; {\n    // Remove the CSS wrapper from the key: `rgba(` &amp; `)`.\n    var keyNumbers = key.substring(key.indexOf(\"(\") + 1, key.lastIndexOf(\")\"))\n\n    // Split the key into red, green, and blue, discarding the alpha (transparency).\n    var keyRGB = keyNumbers.split(\", \", 3)\n\n    // Convert the RGB values into a hex code.\n    var keyHex = \"#\" + ((1 &lt;&lt; 24) + (parseInt(keyRGB[0]) &lt;&lt; 16) + (parseInt(keyRGB[1]) &lt;&lt; 8) + parseInt(keyRGB[2])).toString(16).slice(1);\n\n    // Save the key's value into our new array, with a new key.\n    newArray[keyHex] = colorCounts[key]\n}); \n\n// Sort the new array in descending order, and output it.\nvar sortedArray = Object.fromEntries(\n    Object.entries(newArray).sort( (a,b) =&gt; b[1] - a[1] )    \n);\nconsole.log(sortedArray)\n\n\nAfter using this script, your Console should look like the below. Notice the #000000: 103500, #ff6208: 25500, #3bd8ff: 16700, that looks a lot like a sorted list of hex colour codes!\n\n\n\nUsing the raw data\n\nThe final step is right clicking the outputted array, and selecting “Copy object”:\n\n\n\nYour data is ready to put somewhere! I usually use VSCode:\n\n\n\nEnjoy! 🎉\n"
    } ,
  
    {
      "tags"     : "MVP, Software, Process",
      "title"    : "How an MVP-inspired approach to small feature development can improve your work's visibility & flexibility",
      "excerpt"  : "In the last ~20 years, MVP releases have thankfully become the standard way of developing software. However, this mindset can be taken further, and used as a way to work on an individual ticket or feature, even as a solo dev. Why? Well, here’s a whole post full of motivations…\n",
      "url"      : "/using-mvp-to-develop-features/",
      "date"     : "Aug 29, 2022",
      "content"  : "In the last ~20 years, MVP releases have thankfully become the standard way of developing software. However, this mindset can be taken further, and used as a way to work on an individual ticket or feature, even as a solo dev. Why? Well, here’s a whole post full of motivations…\n\nThe traditional approach\n\nFirst of all, a clarification on what I mean by using MVP on an individual ticket. I don’t mean releasing simple versions of small features, although that may be beneficial. Instead, I mean the concepts behind MVP development can be used whilst implementing a new feature, even if it is only a few days work.\n\nFor example, perhaps you need to build a new checkout flow. The obvious sub-tasks, with time taken, might be:\n\n  1 day: Implement the API calls, using fake triggers.\n  1 day: Perform any local database schema changes and migrations, using fake data.\n  2 days: Build any UI according to the design, using fake data.\n  2 days: Connect these all together.\n  1 day: Test, fix any problems that are uncovered.\n\n\nThis works! The feature is delivered, and so long as the specifications were perfectly defined, it might be the best approach.\n\nHere’s a representation of this workflow. The x-axis is time, y-axis is externally visible progress, where the thick black line represents completion.\n\n\n\nWhat’s wrong with it?\n\nObfuscated progress\nWith this approach, the progress that can be shown to product managers / stakeholders is only on the UI related days. Instead of being a steady progression, the progress seems to move in jumps. For example, it looks like zero progress is being made the first 2 days, when this is actually probably the most challenging work.\n\nIll-defined work\nAdditionally, in the real world tickets… sometimes aren’t so well defined. Perhaps you need to talk to an API that isn’t quite finished yet. Perhaps the design is still subject to change. Perhaps you need to coordinate your changes with other features affecting a database. All of this leads to work being redone in the final step, and almost finished tickets seemingly getting “stuck” in an unfinished state for days.\n\nThis means any changes might cause our progress to end up looking more like:\n\n\n\nNot very encouraging or predictable for the developer or stakeholders!\n\nWhat’s the MVP approach?\n\nInstead of building each part of the feature in isolation and then wiring them together, what if you do the wiring first? This leaves us with sub-tasks of:\n\n  1 day: Add a placeholder UI, add placeholder database fields, and the bare essentials needed for an API call.\n  1 day: Connect these all together.\n  1 day: Finish API work “good enough”.\n  1 day: Finish Database work “good enough”.\n  1 day: Finish UI work “good enough”.\n  1 day: Test, fix any problems that are uncovered.\n  1 day: Refactor / tidy up all work from “good enough” to “finished”.\n\n\nOkay, so our feature took 7 days before, and now takes… 7 days. How is this any better? Well, the end result is about the same, but with a few advantages during development.\n\nWhat’re the advantages?\n\nDaily progress visible to all\n\nAn immediate and selfish benefit is the motivational boost gained from seeing visible progress day by day instead of merely knowledge that a certain class now performs as expected. Arguably more importantly however, this progress is also visible to anybody who is interested. Whether this is from automated CI/CD builds or manual demos, being able to visually show your progress to a non-technical audience at any time is a crucial ability for building trust and reliability.\n\n\n\nNo nasty surprises!\n\nEver got to the very last stage of a feature, then realised a blocker that requires rethinking the whole approach? It’s a painful experience, and whilst it ideally should be avoided by rigorous refinement, any traditional way of working on a feature will experience this sometimes.\n\nUsing the MVP approach, on the very first day you have full confidence the basic idea works. Discovering this on Day 1 vs Day 5/6 can be the difference between a project succeeding or failing, as well as drastically different levels of stress!\n\nFlexibility until the very end\n\nFeatures often have unexpected minor issues as they are being finished, perhaps an unexpected error case, or a design / API change. Using the initial approach, if we’ve already finished &amp; tidied that aspect of the feature any changes require redoing “finished” work and wasting time. Using the MVP approach, all the tidying and refactoring happens at the end, so minor changes are no problem.\n\nTesting throughout\n\nBy having a (just about) functioning demo of your feature ready from the start, you’ll end up testing your own work constantly throughout. Simple bugs like a back button not working will turn up whilst you’re trying to implement something else, and by then then you’ll fully understand the user flow. This will also give you an insight into any potential performance issues or confusing aspects. Using a traditional approach, you’ll only use your feature like a real user during the UI development stage or the fixing at the very end.\n\nEasier to tidy code\n\nWhilst finishing and tidying sections as you work on them might produce tidier separated sections of code, will they stay that way? During the connecting and fixing stages, the oh-so-clever architecture might suffer from a workaround or two, yet you’ll be too deeply invested to refactor it completely.\n\nIf you accept that all areas will be tidied during dedicated time at the end, you can instead focus on the actual functionality. This does of course require keeping track of the areas that need tidying, and isn’t a license to skip this essential work! The overall architecture also needs planning out in advance regardless of approach.\n\nTidying once a feature is completed also lets you tidy according to what is best for the entire system, not just each section in isolation. For example, a class you initially thought should be generic can perhaps actually be a concrete implementation, letting you get rid of some earlier messy generic-handling code.\n\nYou could release at any time\n\nI know I just said this approach doesn’t give you a license to skip the essential refactoring and tidying, but… you can if absolutely necessary. Instead of the feature being utterly useless until the very end, you could technically merge &amp; ship your feature at any point after the first first day. Of course it would be awful, missing features, and be full of bugs, but you have the capability!\n\nThis shouldn’t come up often, but the ability to decide to skip additional functionality and just launch is very powerful.\n\nYour bus factor improves\n\nUsing a traditional approach, the overall approach likely exists in your head for most of the development process. You could build all the components, but if you were hit by a bus would someone else know how to wire them together? Probably not.\n\nWith the MVP approach, the plan is immediately visible. If you disappear halfway through development (e.g. on holiday, somewhat less drastically!) another engineer can likely pick it up with minimal handover. This is especially true during the fixing / tidying stages, where the hard work is already finished.\n\nWork “breaks” are possible\n\nUsually, if you get stuck whilst developing a feature, you just have to keep trying or pause work on the ticket until you’ve solved the problem. Using the MVP approach, you can take a “break” by working on another aspect of the ticket, letting your subconscious consider the tricky problem blocking your progress.\n\nI’ve often found myself stuck on a complex problem and taken a break to do some relatively straightforward UI work, then by the time I get back to my original task the approach is obvious. I actually encourage having “break” tickets anyway (I often use crash fixes), but doing this within the feature avoids starting new work whilst existing work is stuck.\n\nConclusion\n\nWhilst this approach clearly has many advantages for the flexibility and visibility of your work, it’s not without some downsides.\n\nNon-feature tickets sometimes can’t be completed this way, as each section of the work truly does require the previous stages to be completed (e.g. a database schema must be completed before a migration script can be generated). Even for feature tickets, dependencies between stages are sometimes inevitable, so this technique should be a “use if possible” approach, not a “use no matter what”.\n\nFinally, this way of working definitely isn’t for everyone, and what works best for me might not work at all for you. However, I’d encourage at least giving it a go the next time you have a standalone feature ticket with various parts. You might discover a new way of working!\n\n"
    } ,
  
    {
      "tags"     : "Jekyll, GitHub, Comments",
      "title"    : "How to migrate from Utterances to Giscus for Jekyll comments",
      "excerpt"  : "Since migrating from Wordpress to Jekyll, this blog (and my non-tech blog) has used Utterances for comments, which creatively uses GitHub issues for comment hosting. However, since then GitHub has released the “Discussions” feature which… is a much better fit! Luckily, Giscus is a way to use these, and can easily be migrated to.\n",
      "url"      : "/migrating-from-utterances-to-giscus-comments/",
      "date"     : "Aug 14, 2022",
      "content"  : "Since migrating from Wordpress to Jekyll, this blog (and my non-tech blog) has used Utterances for comments, which creatively uses GitHub issues for comment hosting. However, since then GitHub has released the “Discussions” feature which… is a much better fit! Luckily, Giscus is a way to use these, and can easily be migrated to.\n\nI’ve now migrated both sites’ comments across to Giscus, and whilst it was a relatively simple process there’s no all-in-one guide currently. The short version is we’re going to enable GitHub discussions, configure Giscus, add it to our Jekyll blog, then migrate comments!\n\nAn overview of Giscus\n\nGiscus is extremely similar to Utterances, with 3 main improvements:\n\n  It uses GitHub discussions instead of issues, making it less of a hacky implementation (comments logically aren’t issues, they’re discussions!).\n  It adds plenty of new features such as sorting comments, adding reactions to the main post, lazy loading comments, multiple languages, self-hosting the bot, and advanced options.\n  It’s actually being maintained and updated! Constrastingly, Utterances hasn’t been touched in 6 months…\n\n\nIn addition to these benefits, it keeps all the original benefits of Utterances, namely:\n\n  Open source\n  No tracking / adverts / paid plan\n  Lightweight\n\n\nUnfortunately, it’s worth mentioning it also has the same drawback, a scary-looking auth screen when users first comment. It’s been a known issue for years, and the app can actually only access discussions on the repos it is added to!\n\nStep 1: Preparing your repository\n\nBefore Giscus can be enabled, your repository’s discussions need to be prepared. First, enable discussions on your repository’s settings page. This will automatically create a new placeholder discussion, feel free to delete it.\n\n\n\nNext, we want an announcements-style discussion category (so only admins / Giscus can create topics, but anyone can reply), without reusing the “Announcements” category (since we may still want to make announcements!).\n\nTo do this, just click the edit icon next to categories on your repository’s discussion page, delete any you don’t need, and add your new category:\n\n\n\nOnce you’re done, your discussion categories should look something like:\n\n\n\nStep 2: Preparing Giscus\n\nFirst of all, we need to add Giscus, and give it permissions to manage discussions in any repositories we want to use it on:\n\n\n\nNow we’ve installed the app, we can use the Giscus project page’s handy tool to configure the comments.\n\n\n  Enter your repository in the text field (in the format JakeSteam/blog-programming).\n  Select how you want to map discussions to posts. I recommend leaving it on the default pathname setting, and not enabling strict title matching, as this will prevent easy post migration (more info).\n  Select your new “Comments” discussion category.\n  Select your features. I enabled reactions and lazy loading.\n  Select your theme. I just used “GitHub Light”, but you can even use custom CSS here!\n\n\nYou’ll now have a big block of JavaScript ready to embed in the next step! Here’s how mine looks, if you want to compare:\n\n&lt;script src=\"https://giscus.app/client.js\"\n        data-repo=\"JakeSteam/blog-programming\"\n        data-repo-id=\"MDEwOlJlcG9zaXRvcnkzNTk5Mzc1OTM=\"\n        data-category=\"Comments\"\n        data-category-id=\"DIC_kwDOFXQ2Oc4CQ06o\"\n        data-mapping=\"pathname\"\n        data-strict=\"0\"\n        data-reactions-enabled=\"1\"\n        data-emit-metadata=\"0\"\n        data-input-position=\"bottom\"\n        data-theme=\"light\"\n        data-lang=\"en\"\n        crossorigin=\"anonymous\"\n        async&gt;\n&lt;/script&gt;\n\n\nStep 3: Preparing Jekyll\n\nFor this step, all you need to do is add that block of JavaScript to your Jekyll post.html page. If you don’t have a custom post page yet, the Jekyll docs have a guide.\n\nOptionally, a more Jekyll-y approach is to extract the IDs into your _config.yml file, and reference them in your post.html. This approach can be seen in my migration commit, all we’re doing is:\n\n  Add giscus_repo_id: MDEwOlJlcG9zaXRvcnkzNTk5Mzc1OTM= etc to your _config.yml.\n  In the JavaScript, replace the existing repo ID definition with data-repo-id=\"{{ site.giscus_repo_id }}\".\n\n\nRun your site, and you should be able to create new discussions &amp; leave comments! Nice! However… don’t forget about the existing comments.\n\nStep 4: Migrating Comments\n\nFirst, the good news: Issues can be migrated into discussions, and Giscus will be able to use them automatically. All existing comments will be kept, along with the authors and reactions.\n\nAlas, the bad news: Issues need to be migrated manually, one by one. GitHub has an official guide, just make sure you select your “Comments” category for migrated discussions:\n\n\n\nOnce they’re all migrated, you’re done! Woo!\n\nConclusion\n\nOverall, the migration seems a no-brainer. Giscus has all the features and benefits of Utterances, with plenty of additional options as well as a more logical place on your repository!\n\nIf you’re currently using lots of custom Utterances styling, it’s worth noting that the design has changed slightly (to match the discussions UI instead of issues UI):\n\n\n  \n    \n      Utterances (default)\n      Giscus (default)\n    \n  \n  \n    \n      \n      \n    \n  \n\n"
    } ,
  
    {
      "tags"     : "Firebase, Crashlytics",
      "title"    : "From 99% to 99.99%, why & how to chase 100% Crashlytics crash-free users",
      "excerpt"  : "In services with uptime, availability is often measured in the number of 9s, e.g. “4 9s” is 99.99% uptime. Whilst installed apps themselves don’t tend to have uptime in the same way, they do have another critically important metric: % of crash-free users! I’ve always heavily focused on this metric, so here’s some of the things I’ve picked up whilst chasing 100%.\n",
      "url"      : "/chasing-100-percent-crash-free-users-on-mobile/",
      "date"     : "Apr 25, 2022",
      "content"  : "In services with uptime, availability is often measured in the number of 9s, e.g. “4 9s” is 99.99% uptime. Whilst installed apps themselves don’t tend to have uptime in the same way, they do have another critically important metric: % of crash-free users! I’ve always heavily focused on this metric, so here’s some of the things I’ve picked up whilst chasing 100%.\n\nFor context (and, okay, a little brag), I led the Android app of ITV Hub from 98.2% -&gt; 99.7% crash-free users, and Photobox from 99.10% to ~99.98%.\n\nWhat is “crash-free users” measuring?\n\nFirst of all, what are crash-free users? Well, it’s an aggregation over time of how many of your users in a given time frame experienced a crash. The Firebase docs go into this in a bit more detail, but essentially if 1000 people use your app in a day, and 10 of them experience a crash, you have 99.9% crash-free users.\n\nThe impact of this obviously depends on the size of your userbase. For some of my smaller apps, having 90% crash-free users is fine, as it’s only 1-2 people experiencing crashes. For something like ITV Hub, this would be tens of thousands of people!\n\nWhy improve crash-free users percentage?\n\nSo, who cares? Crashes happen, right?\n\nIn larger companies, most aspects of an app will be monitored and improved by product / design / marketing / engineering employees. Whether this is the impact of an email campaign, A/B testing a screen design, or customer-exclusive discounts, these all take significant effort to introduce a minor uplift in sales / users. Crashes however, skip this process entirely, yet may be causing more attrition than anything else combined!\n\nFrom my experience, this is because engineering alone are generally responsible for the crash-free rate, whilst all other initiatives have design and product input. This leads to a lack of visibility, and ultimately no incentive to actually improve the metric unless an engineer champions it…. like I am now.\n\nReflects a real problem for real people\n\nFirst and foremost, this isn’t a metric like conversion rate tracking how many users had a positive interaction. Instead, it is tracking how many had a catastrophic experience.\n\nDepending on when and how an app crashes, it might be barely noticeable (e.g. this crash when a user unlocked their phone whilst Chromecasting) or be completely catastrophic (e.g. a crash on app startup I recently introduced (and fixed!)). Each of those crashes can very easily be a permanently lost user, who might leave a negative review and tell their friends how awful the app is, leading to a single programming typo causing thousands in lost revenue. Not great.\n\nCrashes beget crashes\n\nSo, let’s say your app crashes when the user opens it at exactly midnight on February 29th. Pretty edge case, so it’s fine to just leave it, right?\n\nNope! When your app crashes, it can permanently damage the installation. For example, if it crashes halfway through a bulk database update, the database could become corrupted, or even worse only partially updated. This could then cause seemingly impossible data mismatch issues days or weeks later, wasting hours of time for the user, customer service, and developer.\n\nIf the crash had been fixed as soon as it was noticed, and safety checks for any affected user data implemented, this could have been avoided weeks ago.\n\nInvestigations can reveal underlying / upcoming issues\n\nCrashes don’t come out of nowhere (well, almost never). Instead they are a symptom of programming issues, from accidentally trusting a variable to be non-nullable to assuming a device will always have a certain characteristic (especially prevalent on Android devices, some of which defy all expectations!).\n\nAs such, during the investigation into a crash the root cause is often a future problem lying in wait. I previously experienced a rare crash around device Widevine DRM capabilities. We ignored it as it was only occurring on “Android TV boxes”, the sometimes legally shady devices that aren’t certified to playback encrypted content. A few weeks later however, we discovered a newly released OnePlus phone had somehow yet to gain the certification, so would crash too!\n\nThe “fix” was to check the DRM was supported (despite all normal phones &amp; tablets having it), and trying to help the user understand what was wrong by showing an error message. This approach helps users find a solution themselves, and is a memorable example where I ignored a crash due to the unconventional device and regretted it.\n\nEasily understandable metric\n\nWhen expressing the need for tech debt reduction work, most engineering reasons realistically will have little impact on non-engineers as they’re not measurable. “The codebase sucks” is an awful argument, “500 users a day are experiencing crashes in our photo editor” is excellent. Crash-free users works as both an indicator of the app’s current state, as well as a tool to measure the impact of any changes, free from metrics such as conversion that are easily contaminated by other initiatives.\n\nSelfishly, “improved crash-free users from 99.7% to 99.95%” is also an excellent thing to see on a CV! It implies the engineer cares about real users, understands their work is not just code, whilst also being an easy metric to talk about and share with outsiders.\n\nAmazing effort to reward ratio\n\nFinally, crash fixing (at least on Android) is often pretty easy. There are absolutely times when a single crash can take weeks, but in my experience almost all crashes are easy fixes. Maybe a value is unexpectedly null, maybe a variable can take longer than expected to initialise, issues like this can often take longer to write the PR than fix.\n\nBecause of this, a few hours a week of my time has significantly improved the app experience for tens or hundreds of thousands of users. It’s somewhat sobering to consider that my almost hobbyist crash fixing could easily have made my employers more money than any major new feature / improvement I’ve actively developed!\n\nHow to improve crash-free users percentage?\n\nAlright, so hopefully at least one of the points above has convinced you that the crash-free users % at least needs to be looked at occasionally, and improved if possible.\n\nSo… how?\n\nHave the information you need, and use your tools\n\nYou can’t fix a crash if you can’t see what’s going on. Most apps have far too many various tracking solutions already in place, and they’re probably good enough if used properly.\n\nI’ve always used Crashlytics, and it actually has a custom logging feature built in. However, it becomes drastically more powerful when your app also uses Google Analytics (GA), which most do. The GA events are automatically connected to the crash, meaning you get a detailed history of the user’s actions before the crash.\n\nThis is unbelievably helpful when tracking down a rare crash, especially when combined with custom user keys and event parameters. For an example, here’s a recent crash’s stack trace:\n\n\n\nOur app’s code isn’t even mentioned here! A transaction, somewhere, is too large. Unsolveable, right? Well, let’s take a look at the logs:\n\n\n\nAh! The user is uploading photos! Alright, now we know the screen and actions taken, so have a starting point. However, we test upload pretty often, how come we haven’t experienced this ourselves? Maybe there’s a clue in the user keys…\n\n\n\nWell, we don’t test uploading 846 images that often. From this, we can pretty reliably conclude that inside our image uploader we are using too much metadata per image, leading to crashes on high image counts when passing this data around. Without looking at a single line of code, we’ve identified a likely cause and fix for a crash!\n\nBuild a routine\n\nPersonally, I don’t think having a “crash fixing week” or similar is super beneficial. Crashes are constantly being introduced into an app and accumulate, so fixing as many as possible every few months means easily fixable crashes spend weeks in the wild.\n\nInstead, fix crashes little and often. At Photobox, we use approximately weekly releases. I use Crashlytics to monitor the latest release, and will try to fix the top 2-3 crashes for the next week’s release. This way, any newly introduced crashes are fixed, and historical ones eventually are too.\n\nAdditionally, by constantly maintaining the crash rate, any crashes caused by a new architecture / approach / library can be quickly fixed before the use of it spreads further in the codebase.\n\nMonitor monitor monitor\n\nYou can’t improve crash rate if you aren’t looking at crashes! Firebase has various options for integrating with Slack, Jira, PagerDuty, and email, make sure you’re at least keeping an eye on high velocity crashes.\n\nI also have a Crashlytics tab filtered to the latest release pinned on Chrome, and quickly check it each morning to make sure we’re still at 99.9%+ crash-free. Only takes a second, and has caught a few issues before they’ve escalated.\n\nTake code quality seriously\n\nApproximately a million posts have been written about programming styles, architectures, paradigms etc, so I won’t cover any of those! Instead, I’ll just say tools like lint &amp; detekt and decent PR processes exist for a reason. Use them.\n\nThe only crash that doesn’t impact your crash-free percentage is one that never makes it to real users.\n\nPublicise your number\n\nPerhaps most importantly, take pride in your crash-free rate! Whilst sales, conversions, and even store rating may be monitored and bragged about in Slack and all-hands presentations, crash rate rarely gets mentioned. By making it a public statistic, there’ll be an extra incentive to maintain it, as well as allowing everyone to be aware of the current app stability.\n\nAt Photobox a colleague posts weekly about the crash rate (and other key metrics) in an app team internal channel, allowing non-engineers to keep an eye on it. Whilst realistically these numbers are pretty similar week to week, it’s a great way to make sure the number doesn’t slip.\n\n\n\nThe crash rate is also mentioned when it hits a new milestone in wider meetings with hundreds of people, and should absolutely be celebrated as much as a new product launch (so long as it isn’t a temporary boost!). We celebrated when we hit our first 100% crash-free day, although I’m fully aware that’s not possible when working on a larger app, and is somewhat luck-based.\n\nBe realistic\n\nFinally, accept that you won’t consistently reach 100% crash-free users. On smaller apps you may hit this occasionally, but hitting it for longer periods is impossible. In decreasing order of likelihood, this is due to:\n\n  Continued development introducing new crashes.\n  The sheer variety of Android hardware and software causing a single unheard-of manufacturer’s devices to crash when running your app.\n  Crashes caused by third party libraries.\n  Crashes caused by the user interfering with your app via storage editors.\n  Crashes caused by the device itself being unstable, e.g. battery removed, SD card removed, storage wiped.\n\n\nBecause of this, “4 9s” is the most you can hope to achieve, and coincidentally is the maximum level of detail shown in Crashlytics. If you’re seeing all 9s, your app is phenomenally stable!\n\nConclusion\n\nIn conclusion, time to take a cold hard look at your app’s crash rate!\n\nHopefully this post has convinced you how vital a metric crash rate is, as well as providing you with the techniques and tools to make it a metric to be proud of.\n\nOh, and remember every app has a bad day…\n\n\n"
    } ,
  
    {
      "tags"     : "Google Play, Education",
      "title"    : "A brief review of the (free) Google Play Store Listing Certificate as a developer",
      "excerpt"  : "Back in December, I got an email about something called the “Google Play Store Listing Certificate”. It seemed pretty relevant to my job, and I finally got round to completing it! It’s mostly targeted towards digital marketers, but it has value for engineers publishing on the store, so here’s a short unbiased review.\n",
      "url"      : "/a-brief-review-of-google-play-store-certificate/",
      "date"     : "Mar 25, 2022",
      "content"  : "Back in December, I got an email about something called the “Google Play Store Listing Certificate”. It seemed pretty relevant to my job, and I finally got round to completing it! It’s mostly targeted towards digital marketers, but it has value for engineers publishing on the store, so here’s a short unbiased review.\n\nYou can read an overview of the certificate on the official site, essentially it’s a free qualification intended to help digital marketers get into working with the Google Play Store. Here’s my certificate, it can also be added to LinkedIn!\n\nThe certificate process\n\nThe process was straight forward, with it taking 2-3 hours from first deciding to complete the certificate to finishing the exam. Here’s what’s involved:\n\n\n  Work through the ~13 sections of the study guide, each taking between 5 and 10 minutes.\n  Register for an account on WebAssessor.\n  Complete the timed exam of ~60 multiple choice questions.\n  Receive an immediate pass / fail, with a certificate being emailed to you within a day or so.\n\n\nThe study guide content\n\nAll of the study guide’s content is available without registering, and it’s essentially a structured summary of the key points from Google’s Developer Policy Center.\n\nIt’s very readable and well written, with plenty of interactive elements (tabs, expandable areas, fictional conversations etc) to keep the content engaging. Let’s use the painfully dry sounding “Track installs, uninstalls, and trends with Play Console statistics” section as an example.\n\nThe learning material starts with an overview of why these metrics matter, what you’ll be learning in this section, and how to actually use Google Play Console. Simple techniques like hiding parts of information behind a tabbed interface forces the reader to actively engage, instead of just passively scrolling through a wall of text:\n\n\n\nThe next part of the page, as with many other Google training resources, features simple artwork that complements dull descriptions, and makes the information easier to parse. Each image requires interacting with to display the description, again encouraging the reader to be actively involved in the learning process:\n\n\n\nThis technique of hiding content behind very intuitive interactions continues throughout, with expandable question &amp; answer sections, fictional conversations, and clickmapped screenshots. This mixture of different interactions and a visually appealing interface really does make the learning process easier, it’s evident that significant invisible work has gone into the resource.\n\n\n\nI’ve skipped over a few sections of this page, but the above examples should be plenty to get a feel for the information’s ease of access. Finally, the reader is informally quizzed on two simple questions that are well crafted to be easy if the content has been engaged with, and impossible otherwise:\n\n\n\nOverall, the material was excellently laid out, and I genuinely wish more online training resources took notes. Techniques like breaking the page up into smaller, easily digestible segments with a variety of visual elements are effective enough that I’m intending to change my own documentation style as a result!\n\nDespite spending perhaps 90-120 minutes reading through all the content, it didn’t feel onerous or challenging, and the microinteractions were pleasing enough to motivate continuation. As someone who reads a lot of fiction &amp; non-fiction, I can recognise excellent writing even if I can’t write it myself yet!\n\nHowever, I do want to point out that the content is not going to change your outlook on life or solve any app-related problems you’re encountering. If you already publish Android apps, or market them, you’ll likely know 70-80% of the content already. As someone who used to handle the entire publishing process I’d estimate I knew around 90% of the content, with the unknown aspects being those a mobile SEO expert would likely already know, e.g. custom store listings, analytics, tracking users.\n\nThe exam\n\nThe exam was… honestly too easy. I’m not trying to show off when I say that, honest!\n\nYou have 5 hours to complete 60 multiple questions, and can open new tabs or Google questions as much as you like. Most of the questions are evidently written after looking at the learning material, with all of them being directly answerable by finding the relevant page in the study guide. You can come back to questions later, and there’s no microphone / webcam requirement, or any identity verification.\n\nThat being said, the exam certificate in general is obviously intended to get people reading the content, so it absolutely succeeds in its’ goal. It isn’t meant to be a formal qualification, so the laxer difficulty and requirements make sense.\n\nOnce you’ve completed your exam, you can submit your details to be included in a global directory of Google Play Store Listing Certificate holders. I unfortunately encountered an issue here where I couldn’t fill in the form, as it’s the same form used for the Associate Android Developer Certificate I acquired a few years ago! This is unlikely to be true for most people though, and to be honest I’m yet to see any benefit from this global directory.\n\nReview\n\nThe Google Play Store Listing Certificate is an excellent free resource, and I really hope it’s the first of many similar certificates. The overall style reminded me of the Google Codelabs (very high quality introductions to technical topics), but non-technical topics are often relegated to a collection of help articles.\n\nWhilst gamification of learning obviously has pros and cons, simple elements such as progress bars, checkboxes, and a certificate at the end really increases the motivation and satisfaction in learning. I would absolutely not have spent a couple of hours reading information on Google Play listings, but adding some kind of reward at the end made me do it happily, and now spend time recommending it to others!\n\nIn conclusion, if you’re a developer / marketer / product owner working with the Google Play store, this is a really good use of your time. It’ll help refresh some topics, and probably clarify a few misconceptions that everyone picks up when learning things on the job.\n\nIt’s free, and no registration is needed to look at the resources. And no, this wasn’t a sponsored post!\n\nhttps://play.google.com/academy/certificate/\n"
    } ,
  
    {
      "tags"     : "Jekyll, CSS",
      "title"    : "Fixing Jekyll Anchor Headings links for multiline headings",
      "excerpt"  : "As mentioned a few weeks ago I’m now using the jekyll-anchor-headings scripts to add links to each header. This works great, but… unfortunately has side effects if the header is more than one line. Time to fix that!\n",
      "url"      : "/fixing-jekyll-anchor-links-for-multiline-headers/",
      "date"     : "Mar 20, 2022",
      "content"  : "As mentioned a few weeks ago I’m now using the jekyll-anchor-headings scripts to add links to each header. This works great, but… unfortunately has side effects if the header is more than one line. Time to fix that!\n\nThe problem\n\nWhen the header is multiline, all lines after the first have an incorrect indent making them appear misaligned with the rest of the post:\n\n\n  \n    \n      Before\n      After\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nObviously this isn’t a big deal, but it was annoying enough that I decided to fix it! Luckily, the fix was relatively simple, converting the existing padding-left &amp; margin-left solution to a text-indent solution.\n\nThe fix\n\n\nOldNew\n\n\n\nh2 {\n    margin-left: -18px;\n    padding-left: 8px;\n}\n\n\n\n\n\n.post-content h2 {\n    text-indent: -10px;\n}\n\n\n\n\n\nThe previous solution used margin-left which applied a margin to the entire header, and padding-left which applied padding to every line of the header. This was fine for single line headers, but caused issues when the header spread over multiple lines, as only the first line is affected by the added &lt;a&gt; permalink.\n\nThe end result is additional header lines not being affected by the margin, and being offset too far to the left.\nThe solution was to use text-indent, which only indents the first line, where the added permalink is included.\n\nAdditionally, I noticed the indentation was applying to the homepage (which didn’t include the anchor heading plugin), so changed the CSS to only apply on a post by adding the .post-content selector.\n\nHere’s the full CSS change, but essentially you’re just replacing all of the hX CSS classes in the example with:\n\n.post-content h2 {\n    text-indent: -10px;\n}\n\n.post-content h3 {\n    text-indent: -8px;\n}\n\n.post-content h4 {\n    text-indent: -6px;\n}\n\n.post-content h5 {\n    text-indent: -4px;\n}\n\n.post-content h6 {\n    text-indent: -2px;\n}\n\n"
    } ,
  
    {
      "tags"     : "JavaScript, Web",
      "title"    : "How I built the Google Play purchase history analyser",
      "excerpt"  : "I just added a Google Play purchase history analyser on my non-programming blog, along with instructions, and thought I’d save the technical details of the JavaScript project for here!\n",
      "url"      : "/how-i-built-google-play-purchase-history-analyser/",
      "date"     : "Mar 13, 2022",
      "content"  : "I just added a Google Play purchase history analyser on my non-programming blog, along with instructions, and thought I’d save the technical details of the JavaScript project for here!\n\nThere’s a full repository available for the analyser, or the script actually used.\n\nOverall flow\n\nOverall it’s a pretty simple script, convenient as my JavaScript is very rusty!\n\nHere’s how it works at a high level:\n\n  Let the user load their purchase history .json file.\n  Parse the file as JSON and loop through every purchase.\n  Add the purchase value to an object in the format summary[groupedByYear][2022][sum], and track total number similarly.\n  Loop through each of our groupings, outputting headers and values in HTML tables.\n\n\nAll of this is client-side JavaScript, so no data protection or server cost concerns!\n\n1. Load purchase history file\n\nFor this, we need a basic HTML input element with a filter, and somewhere to put our output:\n\n&lt;input type=\"file\" name=\"inputfile\" id=\"inputfile\" accept=\".json\"&gt;\n\n&lt;div id=\"output\"&gt;&lt;/div&gt;\n\n\nand a FileReader listener that passes the contents of this file to our handlePurchasesFile function:\n\ndocument.getElementById('inputfile').addEventListener('change', function () {\n    var fr = new FileReader();\n    fr.onload = function () {\n        handlePurchasesFile(fr.result);\n    }\n    fr.readAsText(this.files[0]);\n})\n\n\n2. Parse as JSON &amp; loop through\n\nJavaScript can unsurprisingly parse JSON easily, so we parse &amp; pass our purchases to getPurchasesSummary.\n\nfunction handlePurchasesFile(json) {\n    var purchases = JSON.parse(json);\n    var summary = getPurchasesSummary(purchases);\n    var output = document.getElementById('output');\n    outputSummaries(output, summary);\n}\n\n\nThis function uses reduce as a foreach, and parses the purchase price before ignoring any values with an amount of 0:\n\nfunction getPurchasesSummary(purchases) {\n    return purchases.reduce((totals, purchase) =&gt; {\n        var amount = Number(purchase.purchaseHistory.invoicePrice.replace(/[^0-9.-]+/g, \"\"));\n        if (amount == 0) {\n            return totals;\n        }\n\n\n3. Add values to summary object\n\nHere comes the interesting bit. I wanted to dynamically build up the summary objects without knowing any values in advance. This lets the code be as flexible as possible, and avoids any unusual values being missed. Using purchase type as an example, the values can be Paypal: example@example.com, VISA-1234, or many other values impossible to hardcode.\n\nThe following code is run on each purchase, and passes the summary array (“totals”), grouping name (“Grouped by purchase type”), type of this purchase, and price of this purchase to updateTotals:\n\n        var type = purchase.purchaseHistory.doc.documentType;\n        updateTotals(totals, 'Grouped by purchase type', type, amount);\n\n\nThis updateTotals function exists mainly to make sure all object values are defined before we try to set them. As an example on first run:\n\n  totals may be an empty object. The first if statement will make sure it has totals['Grouped by purchase type'].\n  The second if statement will make sure it has totals['Grouped by purchase type']['Paypal'], along with count and sum entries for this purchase type.\n  Finally now we know the object is prepared, we can increment the count and add to the total sum!\n\n\nfunction updateTotals(totals, fieldName, fieldValue, purchaseAmount) {\n    if (!totals.hasOwnProperty(fieldName)) {\n        totals[fieldName] = {}\n    }\n    if (!totals[fieldName].hasOwnProperty(fieldValue)) {\n        totals[fieldName][fieldValue] = {}\n        totals[fieldName][fieldValue]['count'] = 0;\n        totals[fieldName][fieldValue]['sum'] = 0\n    }\n    totals[fieldName][fieldValue]['count']++;\n    totals[fieldName][fieldValue]['sum'] += purchaseAmount\n}\n\n\nAll the other groupings use similar logic; get the value for this purchase, and pass it to updateTotals with the grouping name. This lets new groupings be added very, very simply, with literally 2 lines of code! E.g.:\n\n        var hour = purchaseTime.getHours();\n        updateTotals(totals, 'Grouped by hour of day', hour, amount);\n\n\n4. Output summary\n\nWe’ve now built up a somewhat complex summary (totals) object, time to actually use it!\n\nAs a very old-fashioned approach, I’m just building up an HTML string by looping through each “grouping”, outputting the title, then outputting the name, count, and sum for each value inside.\n\nThis HTML string is then added to my output div, displaying all the data!\n\nfunction outputSummaries(output, summary) {\n    output.innerHTML = \"\";\n    for (grouping in summary) {\n        var newHTML = '&lt;h2&gt;' + grouping + '&lt;/h2&gt;\\n';\n        newHTML += '&lt;table&gt;&lt;tr&gt;&lt;th&gt;&lt;/th&gt;&lt;th&gt;Count&lt;/th&gt;&lt;th&gt;Total&lt;/th&gt;&lt;/tr&gt;\\n';\n        for (type in summary[grouping]) {\n            newHTML += '&lt;tr&gt;&lt;td&gt;&lt;b&gt;' + type + '&lt;/b&gt;&lt;/td&gt;\\n';\n            newHTML += '&lt;td&gt;' + summary[grouping][type]['count'] + '&lt;/td&gt;\\n';\n            newHTML += '&lt;td&gt;' + summary[grouping][type]['sum'].toFixed(2) + '&lt;/td&gt;&lt;/tr&gt;\\n';\n        }\n        newHTML += '&lt;/table&gt;&lt;br&gt;\\n';\n        output.innerHTML += newHTML;\n    }\n}\n\n\nThis outputs a basic table, which gets stylised by my blog’s existing stylesheets:\n\n\n\nThere we go! A basic but functional analyser, feel free to try it for yourself.\n\nLinks\n\n\n  Google Play purchase history analyser\n  Non-programming blog post about how to use it\n  Proof of concept project\n  Code used for the actual analyser and wrapper page\n\n\n"
    } ,
  
    {
      "tags"     : "Open Source, Gaming, Android",
      "title"    : "Open sourcing Pixel Blacksmith and my other old Android games",
      "excerpt"  : "I originally got into Android development by making a game in my spare time, Pixel Blacksmith. This game ended up becoming way more popular than I could have imagined, and persuaded me to follow app development as a career! Now, I’m open sourcing this and other game codebases.\n",
      "url"      : "/open-sourcing-pixel-blacksmith-and-other-android-games/",
      "date"     : "Mar 9, 2022",
      "content"  : "I originally got into Android development by making a game in my spare time, Pixel Blacksmith. This game ended up becoming way more popular than I could have imagined, and persuaded me to follow app development as a career! Now, I’m open sourcing this and other game codebases.\n\nThese codebases are mostly 5-6 years old, so actually compiling them may be tricky. However, they’ll have a lot of functionality that will still be useful today, so feel free to lift out any useful sections!\n\nThe only excluded game is BocaBase from 6-7 months ago, since I might come back to it.\n\nThe games\n\n\n  \n    \n      Game\n      Screenshot\n      Notes\n    \n  \n  \n    \n      Pixel BlacksmithPlay StoreGitHub Repo\n      \n      My first app, and by far my most successful! With 250k downloads, 1400 commits, and 56 releases, the app still has players despite the awful codebase!\n    \n    \n      Blacksmith SlotsPlay StoreGitHub RepoTrailer\n      \n      A spin-off to Pixel Blacksmith, trying to merge 2 of my favourite categories: slots &amp; RPGs.Unfortunately not very successful, but it’s still the only game I’ve made with an actual storyline and opening cutscene!\n    \n    \n      Connect QuestPlay StoreGitHub Repo\n      \n      Inspired by various “zen loop” games, this expanded the concept to include many “flow” types, a complex puzzle generator, and the ability to share levels by QR code.\n    \n    \n      Pixel BookshopGitHub Repo\n      \n      An unfinished project that would have been the true sequel to Pixel Blacksmith.Basic functionality was implemented, but I never got round to finishing it!\n    \n  \n\n\nLicensing\n\nAll of the repositories use the MIT License, essentially giving complete freedom for anyone to use any part of them for any reason.\n\nThe only exception is some of the graphics for the games, which have been removed (see next section) to avoid accidentally violating copyright!\n\nRedacting images\n\nTo redact the images whilst keeping their dimensions and adding the filename on top for identification, I originally asked SuperUser StackExchange but ultimately ended up figuring out my own solution:\n\nUsing IrfanView’s File -&gt; Batch Conversion/Rename on all images that needed removing, and selecting Advanced options:\n\n\n  Set the image’s brightness to -255 (all black).\n  Add the image’s filename on top:\n    \n      Position the text in the Center.\n      Set the text to $F to use the filename.\n    \n  \n  Overwrite the original image.\n  Modifying the Custom processing order to make sure the text is added last.\n\n\n\n\nThis very confusing screen is also available as a settings.ini file!\n\n\n  \n    \n      Before\n      After\n    \n  \n  \n    \n      \n      \n    \n  \n\n"
    } ,
  
    {
      "tags"     : "Blog, Jekyll, CSS",
      "title"    : "Blog updated (v2.1) with table of contents and anchor links!",
      "excerpt"  : "Whilst Jekyll’s Minima theme is great, there’s a couple of very basic features I wish it had by default. I added the features myself today, and decided to start doing “release notes” style posts for the codebase used in both my blogs!\n",
      "url"      : "/blog-v2-1-with-table-of-contents-and-anchor-links/",
      "date"     : "Mar 6, 2022",
      "content"  : "Whilst Jekyll’s Minima theme is great, there’s a couple of very basic features I wish it had by default. I added the features myself today, and decided to start doing “release notes” style posts for the codebase used in both my blogs!\n\nTable of contents\n\nSome of my longer posts (example) can be quite hard to orientate yourself in, despite the various headings. Adding a table of contents should alleviate this, but I wanted to avoid any JavaScript-dependent solutions or any that weren’t flexible.\n\nIntroducing “Jekyll Pure Liquid Table of Contents”, a very easy to implement solution that meets my requirements! Once I’d downloaded the .html file and added the following to my post.html, it was done:\n\n  &lt;div class=\"toc\"&gt;\n    &lt;b&gt;Jump to:&lt;/b&gt;\n    {% include custom/contents.html html=content %}\n  &lt;/div&gt;\n\n\nOut of the box, this introduces a very simple unordered list of all headings in the post. This is alright to start with, but I wanted to add a little bit of styling.\n\nI decided to make the contents “float” in the top right of the post, hide the list styling, and add a simple border similar to the homepage cards. These changes can be seen in the table of contents CSS.\n\n\n  \n    \n      Site\n      Before\n      After\n    \n  \n  \n    \n      Software\n      \n      \n    \n    \n      Non-software\n      \n      \n    \n  \n\n\nAnchor links\n\nSomewhat related to the table of contents, sometimes I want to link someone to a specific part of a post. Whilst this is technically possibly by manually editing the URL (since Jekyll automatically gives all headers an ID), it’s not very user friendly.\n\nLuckily, the same dev who created the table of contents script also created one to add heading anchors! It’s just as easy to install.\n\nOut of the box it offers a usable but basic experience, adding a clickable character after each heading to get the link. I used the code from one of the provided examples to make this button appears to the left of the headers, and be invisible until the header is hovered over. This makes the link functionality a bit less prominent, whilst still available to those who want it.\n\n\n\nStyling changes\n\nI also decided the non-programming blog needs more of an accent colour. Whilst grey was fine to start with, it’s not very distinctive! For now, only a few elements have had this colour applied, but eventually links should use it too.\n\n\n  \n    \n      Before\n      After\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nComing in v2.2\n\n\n  More comprehensive “accent” styling for non-programming blog.\n  Fix the pagination becoming left-aligned again!\n  Check all headers etc are accessible for visually impaired users.\n\n"
    } ,
  
    {
      "tags"     : "BottomNavigationView, UI, Android",
      "title"    : "Fixing a BottomNavigationView that insists on being too tall",
      "excerpt"  : "At work, we’ve had a bug that has appeared intermittently since before I joined. The navigation bar at the bottom of our app would very rarely become absolutely massive. For seemingly no reason. Today, I finally freed us from this menace!\n",
      "url"      : "/fixing-a-too-tall-bottomnavigationview/",
      "date"     : "Mar 4, 2022",
      "content"  : "At work, we’ve had a bug that has appeared intermittently since before I joined. The navigation bar at the bottom of our app would very rarely become absolutely massive. For seemingly no reason. Today, I finally freed us from this menace!\n\nProblem\n\nTo set the scene, we have an activity_main.xml with a NavHostFragment and a BottomNavigationView. Both Google components used to handle navigation around the app with no changes besides basic styling. These were defined perfectly sensibly inside a ConstraintLayout, yet occasionally we’d see this:\n\n\n  \n    \n      Correct\n      Incorrect\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nAs you can imagine, this was pretty frustrating for the user, having just the tiny top area to actually use! The issue fixed itself when the app was restarted, but on smaller devices made the app almost unusable.\n\nGoogling around didn’t turn up anything useful, mostly people having problems with the bar’s size in general, not in certain situations!\n\nDebugging\n\nWe experienced this rare bug during 2 filmed user sessions of our shopping app, so the videos could be compared to find out what happened. Here were the clues gained:\n\n\n  It only happens for users on their first order.\n  It only happens when a user changes their mind after entering their address, but before entering payment details.\n  The BottomNavigationView had a few hundred pixels of bottomPadding added, despite paddingBottom=\"0dp\" in the XML. Calling .invalidate() / .requestLayout() didn’t change the padding.\n\n\nThrough trial and error, I found our Address Picker screen was to blame. On this screen new users start typing their delivery address, pick it from a list of found addresses, then proceed to checkout.\n\nEventually I realised the empty space on screen… perfectly matched the space the keyboard would take up! So, the keyboard must be involved somehow, despite not being open. Here’s what happened:\n\n\n  When the user is typing their address, the keyboard is obviously visible.\n  When they select an address, our app navigates away from the screen via a slightly convoluted method involving MVVM and a RecyclerView adapter.\n  This navigation action doesn’t explicitly dismiss the keyboard.\n  If the user gets to the homepage without opening the keyboard again, the BottomNavigationView tries to fit above this (invisible) keyboard.\n  We have our giant bottom padding.\n\n\nSolution\n\nI don’t understand why only BottomNavigationView seems affected by this, or quite why it happened, but luckily the solution is pretty easy:\n\nthis.view?.hideSoftKeyboard()\n\n\nJust calling this when an address is selected (AKA the screen with a keyboard is navigated away from) will cause the keyboard to be properly “hidden” when the user gets back to the BottomNavigationView.\n\nA deeply satisfying Friday-last-thing fix to a bug that has plagued the app for years!\n\n\n"
    } ,
  
    {
      "tags"     : "GitHub, Diagrams, Mermaid, Web",
      "title"    : "Using Mermaid for easy GitHub diagrams in Markdown-ish code",
      "excerpt"  : "On most larger software projects, at some point you’ll probably need to use a diagram on GitHub. Whether it’s explaining how components interact, a user’s flow, or project timelines, it’ll happen eventually, usually in a PR.\n",
      "url"      : "/using-mermaid-for-diagrams-on-github/",
      "date"     : "Feb 28, 2022",
      "content"  : "On most larger software projects, at some point you’ll probably need to use a diagram on GitHub. Whether it’s explaining how components interact, a user’s flow, or project timelines, it’ll happen eventually, usually in a PR.\n\nIn the past I’ve used something like LucidChart or Miro, then embedded the image and linked to the original file. However, this means a whole new set of access controls, reliance on a (often paid!) third party, and is overall a pretty bad experience.\n\n\n\nMermaid\n\nHowever, there’s another option, Mermaid! It lets you embed diagrams using intuitive, markdown-ish code. This means you get all the advantages of git, but for gantt charts, timelines, pie charts, database diagrams, flowcharts, etc!\n\nTo use it on non-GitHub sites (like this one) you need to embed the JavaScript and use a div with the mermaid class (official instructions), whilst on GitHub a code block with mermaid is enough.\n\nExamples\n\nFor example, adding a few lines describing a state diagram:\n\n```mermaid\nstateDiagram-v2\n    Stationary --&gt; Moving : Begin moving\n    Moving --&gt; Stationary : Stop moving\n```\n\n\nWill give you a simple but usable diagram! It’s not an image, it’s done in CSS so it can be styled, the text can be copied, you can access it via JavaScript, etc.\n\n\nstateDiagram-v2\n    Stationary --&gt; Moving : Begin moving\n    Moving --&gt; Stationary : Stop moving\n\n\nSimilarly, to easily compare the distribution of some values in a pie chart:\n\n```mermaid\npie\n    title Fruits\n    \"Apples\" : 50\n    \"Oranges\" : 20\n    \"Grapes\" : 9.99\n    \"Passionfruits\" : 12.5\n```\n\n\ngives\n\n\npie\n    title Fruits\n    \"Apples\" : 50\n    \"Oranges\" : 20\n    \"Grapes\" : 9.99\n    \"Passionfruits\" : 12.5\n\n\nFinally, for scheduling work, the very concise:\n\n```mermaid\ngantt\n    title The Chart's Title\n    Task 1: a1, 2020-01-01, 3d\n    Task 2: a2, after a1, 5d\n```\n\n\ngives\n\n\ngantt\n    title The Chart's Title\n    Task 1: a1, 2020-01-01, 3d\n    Task 2: a2, after a1, 5d\n\n\nCheatsheets\n\nTo learn the capabilities of Mermaid, I wrote cheatsheets for all supported Mermaid charts. They can all be embedded in GitHub PRs / issues / wiki pages, and include:\n\n\n  Flowcharts\n  Sequence Diagrams\n  Class Diagrams\n  State Diagrams\n  Entity Relationship Diagrams\n  User Journey Diagrmas\n  Gantt Chart Diagrams\n  Pie Charts\n  Requirement Diagrams\n  Git Graphs\n\n\nTips\n\nFinally, I wanted to mention a few things I discovered whilst learning Mermaid’s capabilities.\n\nFirstly, since Mermaid is essentially a Markdown extension, extensions for VS Code (and other text editors) exist for realtime previewing. This makes writing them very easy, but be aware that the local preview CAN differ slightly from GitHub’s. For example, the Gantt chart above doesn’t work locally for… unknown reasons. Maybe differing Mermaid renderers?\n\nSecondly, the official documentation quality varies a bit. For example every aspect of flowcharts are documented, whilst user journey has a single example. The git graph feature is experimental, and isn’t in their documentation at all!\n\nThirdly, whilst it is extremely powerful, it has quirks. For example when included in a table it seems to reserve space for itself at full size, then shrink down, leaving a big gap:\n\n\n\nFinally, the changelog on the documentation site is very outdated. New versions are being regularly released, with lots of features and fixes!\n\nSummary\n\nOverall, I can’t believe this GitHub feature isn’t more widely known. Being able to include diagrams of classes, databases, user journeys etc in a PR / wiki without a third party service is something I’ve desperately needed! The fact that they’re just code also means they can be stored with the codebase, instead of a /images/ folder or hosted elsewhere.\n\nI intend to convert all of my third party diagrams to Mermaid ASAP, so they can be properly tracked / access controlled, whilst also being far easier to work with than a GUI driven tool. Viva la mermaid!\n"
    } ,
  
    {
      "tags"     : "Google, Security, Phishing",
      "title"    : "A writeup of a very convincing 2017 Gmail phishing scam",
      "excerpt"  : "Waaaaay back in 2017, I experienced the most convincing phishing attack I’ve ever seen. I didn’t fall for it, but it was too close for comfort! I published my notes on Reddit and it got a lot of attention, and ended up in a few news articles.\n",
      "url"      : "/a-writeup-of-a-2017-phishing-scam/",
      "date"     : "Feb 27, 2022",
      "content"  : "Waaaaay back in 2017, I experienced the most convincing phishing attack I’ve ever seen. I didn’t fall for it, but it was too close for comfort! I published my notes on Reddit and it got a lot of attention, and ended up in a few news articles.\n\nCurrently if the images or post are deleted, all the info will be gone forever, so I wanted to write it up permanently here. To summarise the phish: A fake app called “Google Docs” was created. If given access to your account, it emailed all your contacts asking for access to their accounts too.\n\nOriginal writeup\n\nHere’s the steps, as I experienced them &amp; described them on the day:\n\n\n  I received an email that a Google Doc had been shared with me. Looked reasonably legit, and I recognized the sender.\n  The button’s URL was somewhat suspicious, but still reasonably Google based.\n  I then got taken to a real Google account selection screen. It already knew about my 4 accounts, so it’s really signing me into Google.\n  Upon selecting an account, no password was needed, I just needed to allow “Google Docs” to access my account.\n  If I click “Google Docs”, it shows me it’s actually published by a random gmail account, so that user would receive full access to my emails (and could presumably therefore perform password resets etc).\n  Shortly afterwards I received a followup real email from my contact, informing me: “Delete this it’s a spam email that spreads to your contacts.”\n\n\nTo summarise, this spam email:\n\n\n  Uses the existing Google login system\n  Uses the name “Google Docs”\n  Is only detectable as fake if you happen to click “Google Docs” whilst granting permission\n  Replicates itself by sending itself to all your contacts\n  Bypasses any 2 factor authentication / login alerts\n  Will send scam emails to everyone you have ever emailed\n\n\nGeneral notes\n\nSo, pretty scary. Whilst it’s easy to notice mini red flags when investigating the above images now knowing they’re a scam, when it’s a trusted contact inviting you to a document, it’s a lot more convincing.\n\nI’d worked with this contact before on a shared Google doc, they’d been testing one of my games for me. As such, an invite to a document was not at all unusual, and there’s usually no risk in opening a Google Doc anyway.\n\nFor many people, myself included, my gmail account is pretty much the centre of my online life. I use it to login to all services, all password resets go there, it has years of payment records. Due to 2FA (which Google is very wisely beginning to force), my account always felt “safe”, but this phish would have bypassed it completely.\n\nRed flags\n\nI consider myself pretty security-savvy online, but I can absolutely see myself falling for this phish if I was in a hurry or distracted.\n\nThe excellent YouTuber Atomic Shrimp speaks about scams quite often, and his recent video contained a diagram that prompted this post. He discusses the idea that when analysing an email’s trustworthiness, lots of little red flags can add up to make you suspicious. Using it, we can see our phishing scam… doesn’t have any of the flags his scam email did:\n\n\n\nScreenshot from “Nikon Scam Targeting YouTubers - How To Recognise a Scam”.\n\nIn fact, it’s a genuine email from a trusted contact, with believable content, and a seemingly safe URL (no redirects, weird domains, etc). Atomic Shrimp has spoken many times about the risks in ending up clicking a malicious link, so the fact that this phishing scam nearly tricked me is humbling!\n\nHere’s what I should have picked up on in my case, but didn’t, possibly because I was predisposed to trust the sender:\n\n  The initial email was actually addressed to a hhhhhhhhhhhh email, and I was bcc’d. I dismissed this as my contact accidentally entering my email in the wrong field.\n  No information about the Google Doc was included in the email. I dismissed this because it doesn’t seem unusual if the document is private.\n  The concept of “Google Docs wants access to my Google account”. This is actually where I did catch it, and was probably my last chance. This isn’t particularly unusual in a company with as many products as Google, but since I used Google Docs regularly it raised the lucky red flag.\n\n\nWhat happened next\n\nMy post got a lot of attention, since the phishing spread itself extremely quickly (emailed to every contact), and hit at a time when the US was waking up, and the EU was still awake.\n\nIt got the attention of a few Googlers lurking on the subreddit, who raised it internally, and got the initial worm fixed within the hour. Lots of people also contributed ways for G Suite sysadmins to resolve the issue immediately.\n\nThe short term fix was disabling the malicious app that was spreading like wildfire, and long term fixes were being investigated:\n\n\n  We have taken action to protect users against an e-mail impersonating Google Docs &amp; have disabled offending accounts. We’ve removed the fake pages [and] pushed updates through Safe Browsing, and our abuse team is working to prevent this kind of spoofing from happening again. We encourage users to report phishing e-mails in Gmail.\n\n\nQuote from @googledocs on Twitter.\n\nFinal comments\n\nSome alleged source code of the worm was published on the day, and amazingly seems to do nothing malicious beyond spreading itself. Considering the attacker had access to every email in thousands of inboxes, it’s shocking that there were no negative impacts besides a bit of spam. Dodged a bullet!\n\nConsidering the to: hhhhhhhhh@mailinator.com, this worm gave the appearances of a half-finished attack that escaped quarantine. Perhaps a test run of the attack accidentally escaped to a real user, and then couldn’t be contained. However, it used multiple domains and a seemingly fake creator email (in the format first.last@gmail.com), so it’s a mystery who was behind it and why.\n\nConsidering the simplicity of the attack, it’s somewhat surprising that it hadn’t happened before. The attack’s server also slowed down massively from the intense load, so it’s possible the widespread success is what actually stopped the spread!\n\nLinks\n\n\n  The original Reddit post has over 1000 comments, so is worth a read if you’re interested in this tiny bit of internet history.\n  Ars Technica and The Verge did great summaries of the worm on the day.\n\n"
    } ,
  
    {
      "tags"     : "Cloudflare, GitHub, DNS, HTTPS",
      "title"    : "How to disable Cloudflare proxying with GitHub pages on a custom subdomain",
      "excerpt"  : "When creating a new GitHub pages site with Cloudflare’s DNS, the default setting is proxying all data via Cloudflare. This is OK, but Cloudflare can slow down GitHub pages somewhat, and GitHub pages have no bandwidth limits so might as well serve directly.\n",
      "url"      : "/how-to-disable-cloudflare-proxying-with-github-pages/",
      "date"     : "Feb 19, 2022",
      "content"  : "When creating a new GitHub pages site with Cloudflare’s DNS, the default setting is proxying all data via Cloudflare. This is OK, but Cloudflare can slow down GitHub pages somewhat, and GitHub pages have no bandwidth limits so might as well serve directly.\n\nProblem!\nHowever, turning off proxying will… break things. Here’s an example from my settlers site, where Cloudflare was increasing load times from ~100ms to ~300ms:\n\n\n\n\n\nUh oh. This happens because the site previously worked over HTTPS, and now doesn’t, as shown:\n\n\n  \n    \n       \n      Old\n       \n      New\n       \n      Target\n    \n  \n  \n    \n      Cloudflare handles HTTPS\n      Yes\n      -&gt;\n      No\n      -&gt;\n      No\n    \n    \n      GitHub handles HTTPS\n      No\n      -&gt;\n      No\n      -&gt;\n      Yes\n    \n  \n\n\nSo, we obviously need to get GitHub to provision a certificate for us, and handle it all. Unfortunately, it still thinks Cloudflare is handling it all, so won’t provide a certificate. We’ll have to force it.\n\n\n\nNote the misleading “Unavailable for your site because your domain is not properly configured to support HTTPS” error.\n\nSolution!\n\nThe solution is luckily not too tricky, but not at all obvious:\n\n\n  Remove your custom domain (screenshot).\n  Wait a few minutes, refresh the page, and add your custom domain back in.\n  Wait a few more minutes, refresh it a few more times, you should see messages about a certificate being provisioned.\n  Wait yet again, and eventually the HTTPS checkbox will be tickable again.\n  After 5-10m, the DNS changes should propagate and your site will be back up again.\n\n\nIf you’re doing this for a custom domain, not subdomain, you’ll also need to:\n\n  Disable proxying for ALL the A records.\n  Add a CNAME record for www and &lt;yourusername&gt;.github.io to force a certificate to be created.\n\n\n\n\nIf these steps don’t seem to solve it, and troubleshooting doesn’t help, nor the tips in this thread, you’ll need to raise a support ticket!\n"
    } ,
  
    {
      "tags"     : "Windows, Microsoft, Images, PowerToys",
      "title"    : "Using Microsoft's PowerToys for easy image resizing in Windows",
      "excerpt"  : "When I moved from WordPress to Jekyll, I lost out on some of the auto-thumbnail functionality. Whilst I could manually create thumbnails and header images, I started looking for a more efficient solution for my Windows 10 machine. Enter Microsoft’s PowerToys’ Image Resizer.\n",
      "url"      : "/using-powertoys-for-easy-image-resizing-in-windows/",
      "date"     : "Feb 17, 2022",
      "content"  : "When I moved from WordPress to Jekyll, I lost out on some of the auto-thumbnail functionality. Whilst I could manually create thumbnails and header images, I started looking for a more efficient solution for my Windows 10 machine. Enter Microsoft’s PowerToys’ Image Resizer.\n\nMicrosoft’s PowerToys pack by Brice Lambson has been around for just over 2 years, but doesn’t seem very widely used. It has a lot of useful functionality (remapping keys, changing window snapping, always on top, power rename, color picker, previewing for more file types, and more!), but I’ll only be talking about Image Resizer in this post.\n\nInstalling Image Resizer\n\n  Go to the latest PowerToys release on GitHub.\n  Download the attached .exe.\n  Install it as normal, no restart needed.\n\n\nConfiguring Image Resizer\n\n\nIt’s a pretty straightforward utility, with the main options being your desired size presets and the output filename. You can define a custom size when resizing images, but presets are helpful for repetitive actions.\n\nI have 3 presets that I’ll be using for this blog:\n\n  “thumbnail”: Used on the image above, makes a copy of the image that fits within 600x600. For example, a 1200x500 image would be resized to 600x250.\n  “thumbnailsmall”: Used when multiple images are side by side, same logic as “thumbnail” except smaller.\n  “header”: Used for this post’s header, shrinks &amp; crops an image to the necessary size, filling the space.\n\n\nI’ve set my output filename to the original filename with the preset name at the end. For example myimage.png would become myimage-thumbnail.png. There’s a few basic options available:\n\n\n\nThe “Encoding” options are only used if the resize fails, so are very rarely used.\n\nUsing Image Resizer\n\nNow that your basic settings are configured you can actually use the utility. Select a few images, right click, and there’ll be a new “Resize pictures” option in the context menu.\n\nClicking it opens up a dialog with options for what to do with the selected images:\n\n\n\nThe options aren’t explained in the documentation, and can be a little unintuitive:\n\n  Select size: Select from a predefined preset, or perform a custom resize.\n  Make pictures smaller but not larger: This controls whether images should ONLY be shrunk (i.e. for thumbnails) instead of enlarged, even if both of their sides are already within the limits. I recommend leaving this unchecked.\n  Ignore the orientation of pictures: This controls whether images should be rotated to better fit the desired size. I recommend leaving this unchecked.\n  Resize the original pictures: This controls whether the original file should be replaced. I use this for the blog headers, but not the thumbnails.\n  Remove metadata that doesn’t affect rendering: This controls whether irrelevant metadata (e.g. camera used, location, etc) should be stripped out. I recommend ticking this, especially if you’re resizing photos you’ve taken.\n\n\nConclusion\n\nI really, really like this tool! It’s super useful, doesn’t feel bloated, and does exactly what I need it to.\n\nI’m surprised PowerToys aren’t promoted more, especially given Microsoft’s massive impact on the developer community with GitHub (acquired) and VSCode among others. The open source nature of the tools is much appreciated, as are the regular releases. Hopefully the functionality (and PowerToys in general) eventually gets folded into the core Windows build, and reaches a wider audience!\n"
    } ,
  
    {
      "tags"     : "Settlers 3, HTML, GitHub Pages",
      "title"    : "Announcing an online version of the Settlers 3 game manual",
      "excerpt"  : "Settlers 3 is a PC strategy game from the late 90s that I spent countless hours in. It included a very detailed manual on the disc, full of images, tips, and stats. I’ve begun playing the game’s 2018 remaster, and discovered the manual’s original site format was not available anywhere online… until now!\n",
      "url"      : "/settlers-3-online-manual/",
      "date"     : "Feb 17, 2022",
      "content"  : "Settlers 3 is a PC strategy game from the late 90s that I spent countless hours in. It included a very detailed manual on the disc, full of images, tips, and stats. I’ve begun playing the game’s 2018 remaster, and discovered the manual’s original site format was not available anywhere online… until now!\n\nhttps://settlers.jakelee.co.uk\n\nFirst of all, the manual is available in English, French, and the original German. All the images and content should work perfectly, if there’s any problems please raise an issue.\n\nHere’s a few sample pages:\n\n\n  \n    \n      Getting Started\n      Buildings\n      Military\n    \n  \n  \n    \n      \n      \n      \n    \n  \n\n\nAs with this blog and my portfolio, the manual is hosted on GitHub pages. I had to make a few changes to get the site working, and documenting them here might help similar projects.\n\nCase sensitive file names\nThe manual was originally created to run on Windows, and as such had a mixture of uppercase and lowercase filenames. When running on a server, this suddenly became an issue, as one page might link to the incorrect casing of a page!\n\nFile names\nLuckily I’ve used Ant Renamer many, many times before and it can handle bulk renaming of a thousand or so files easily:\n\n\n\nLink paths\nNow the files were all consistent, the links needed to be fixed! I had a bit of trouble with this, but got there eventually with VS Code’s regex find and replace.\n\nI wrote a regex to find every string between href= and .htm (e.g. a href=\"/EXAMPLE/example.htm) using (?&lt;=href=)(.*?)(?=\\.htm). I then replaced all of these with a lowercased version (\\L$1). In most cases this didn’t change anything, but it fixed 60-70 links that were broken. I then repeated this process with .gif suffixes.\n\n\n\nLink extensions\nFinally, I did a simple find and replace for .GIF with .gif and .HTM with .htm, to make sure all the links went to the correct extension.\n\nFile encoding\nNow that navigation was sorted, and the sites looked good, I uploaded them. I sorted out GitHub pages, the DNS records etc, thinking I was done, and checked it in the browser. Only to be greeted by… question marks sprinkled liberally over the sites, especially the German one!\n\n\n\nIt worked perfectly on my machine, but got filled with question marks when served from GitHub pages. Hmmm…\n\nThis ended up taking far too long to diagnose, but I eventually discovered the sites were encoded in iso-8859-2, NOT utf-8. Detecting encoding is much trickier than filetype, as a file can be valid in multiple encodings at once, there’s no guaranteed way to tell. My local files were ambiguous, and Windows / Chrome was figuring it out, but my remote files were explicitly UTF-8 like almost every other page on the internet.\n\nVS Code and Notepad++ both have “convert encoding” functionality, but neither seemed able to actually do the job, and certainly not in bulk. Luckily, File Encoding Checker can do it easily:\n\n\n\nLanding page\n\nFinally, I added a quick and dirty language selector linking to the 3 manuals. Done!\n\nhttps://settlers.jakelee.co.uk\n\n\n\n"
    } ,
  
    {
      "tags"     : "Wordpress, Jekyll, Blogging",
      "title"    : "Why I moved from WordPress to Jekyll",
      "excerpt"  : "As mentioned in a previous post, I finally took the time last weekend to migrate this blog across to a simpler, free solution.\nThis decision wasn’t taken lightly, so I wanted to expand on some of the reasons behind the move, in case others are on the fence. Heads up, this is a rant post!\n",
      "url"      : "/why-i-moved-from-wordpress-to-jekyll/",
      "date"     : "Feb 15, 2022",
      "content"  : "As mentioned in a previous post, I finally took the time last weekend to migrate this blog across to a simpler, free solution.\nThis decision wasn’t taken lightly, so I wanted to expand on some of the reasons behind the move, in case others are on the fence. Heads up, this is a rant post!\n\nFirst I want to briefly summarise the WordPress.org vs WordPress.com situation.\nEssentially, .org is the blogging software itself, .com is a platform selling access to hosted versions of the software, domains, email services, everything to actually run a site.\n\nIn this post “WordPress” usually refers to both of them, or can be determined from context.\n\nHistory of this blog’s migrations\n\nFor context, here’s this blog’s adventures since 2016:\n\n\n  Started off as the free gamedevalgorithms.wordpress.com, obviously via WordPress.com.\n  Moved to gamedevalgorithms.com on a paid plan, still via WordPress.com.\n  Moved to blog.jakelee.co.uk, as I was moving away from game development.\n  Replaced WordPress.com with BlueHost, as I wanted a bit more control and to not have to pay more for minor changes.\n  Left WordPress entirely for Jekyll, for the reasons detailed in this post!\n\n\nWithout any further ado, in descending order of “how much they annoyed me”, here’s my complaints about WordPress:\n\nSecurity\n\nWordPress is famous for suffering from security exploits, even on a fresh install. As an example, a patch 5 weeks ago fixed multiple SQL injection vulnerabilities in the core code, a terrifying threat when considering 43% of sites use WordPress!\n\nThis also doesn’t cover the many, many, many vulnerable plugins, with almost every large plugin having vulnerabilities at some point. From the very few plugins I used, Yoast SEO with 5m+ installs has 18 on record, and Updraft with 3m+ has 8.\n\nAs a site owner, it feels like an impossible task trying to keep your site secure. I intentionally went for a managed WordPress install, so I wouldn’t have to constantly update WordPress, but plugins aren’t included in this.\nDo you enable plugin autoupdates, potentially introducing vulnerabilities but fixing known ones, or disable them, leaving your site open to the known vulnerabilities? Not a great choice!\n\nThis often meant that useful plugins (like the one to backup posts to GitHub) would simply die on later versions of WordPress, and there was no way to fix them. After a few dead plugins, you become a bit bitter.\n\nThe cherry on the security cake? I had to install a third party plugin to protect my site behind 2FA. Would a hacker be able to get through? Probably! Did it ever feel truly secure? Nope!\n\nSpeed\n\nWhilst WordPress can presumably load relatively quickly in other scenarios, my experience on BlueHost was painfully slow.\n\nOf course I was on the cheapest plan, paying a not-insignificant $8.99/mo, but 3-4 seconds loading any page (even via Cloudflare caching) is madness. The internal dashboard took 10 seconds to load, and saving a draft took about as long.\n\nI’m sure the blame is shared between the platform, the hosting, the plugins, and maybe something misconfigured, but it was awful. I actively dreaded opening up the editor, which… isn’t conducive to writing good blog posts.\n\nComfort\n\nRelated to the previous point, I wasn’t particularly comfortable with using the fancy editor, then switching to the raw HTML to occasionally fix things.\n\nAll the documentation, PRs, and even my to-do list is in markdown, why not blog in it too? I can still put little bits of HTML if they’re more convenient, but using a much more concise syntax like markdown feels natural.\n\nThe same applies for data storage and deployment; I use GitHub all day, why not run my site from it too?\n\nUnnecessary\n\nAs you can probably tell from the new site, I’ve always just wanted to do write-ups of technical subjects to help others. I’m not interested in advertising, in guest posts, in fancy features, I just want to share some technical knowledge.\n\nIn retrospect, WordPress is probably the wrong platform for that. In the past I’d used Google’s Blogger, because it was so simple, and just made for blogging. WordPress meanwhile can be used for pretty much anything, and that unfocused potential can be a drawback.\n\nI didn’t need advanced analytics, or multiple users, or a complex editor, or a shop, or anything. I needed a place to put text and images.\n\nControl\n\nI like to think of myself as relatively tech-savvy. I’m a software engineer, I’ve been on the internet for 20 years, I “get” it.\n\nAt least, I thought I did until I used WordPress. Even after 5(?) years of using the platform, I still don’t really understand where the design comes from, where the data comes from, what components make up my site, etc. For those that work on WordPress for a living, I’m sure it makes perfect sense. As someone who knows a bit of PHP / JS / CSS, but hasn’t dived deeply, it’s… a complete mystery.\n\nI suspect if someone is at the “WordPress dev” or “Non programmer” ends of the spectrum, it makes sense, but not for those inbetween (or maybe I’m an idiot).\n\nAdditionally, as I tried to find a solution for just showing code blocks, I went through a few code syntax highlighters. As part of the migration process, I discovered some of my older posts had been completely mangled, with random HTML tags throughout. This kind of thing reinforces my problems with actually owning and controlling my own content! By contrast nobody / nothing can touch this post, even Jekyll will just transform it leaving the original file alone and safe.\n\nEcosystem\n\nThis is probably a “me” issue. As the majority of WordPress users seem to be non-technical (e.g. marketing, bloggers), looking for technical solutions felt very “wild west”-y.\n\nMost of the solutions were a snippet of code via a blog post, with no indication of side effects, risks, etc. Whilst StackOverflow has its issues, the voting and reputation systems at least give some reassurance that running a line of code won’t cause anything to explode.\n\nSimilarly, most of the WordPress blogs understandably cater to this large audience, which means wading through tens of marketing / SEO posts to find out how to change a setting. It ended up feeling like I was very much out of place.\n\nReliability\n\nFinally, this is undoubtedly just a BlueHost issue, but once or twice a year my site would silently go offline. I would have no idea it had happened, would just go to check something and discover it was down. I’d then have to contact support, and get them to… fix whatever they had broken.\n\nConclusion\n\nSo, rant over!\n\nIn summary, I can’t recommend WordPress(.org or .com) to anyone just trying to start a simple blog. Jekyll is worth the time investment if you’re a developer, or Ghost if you’re trying to get paid from posts.\n\nThis quickstart guide for Windows was astonishingly easy to follow, and got me up and running in under 5 minutes, whereas my last attempt resulted in a confusion of Ruby dependencies and package managers!\n\nI’d love to see a company really support and champion Jekyll, perhaps by providing an all-in-one tool for configuring &amp; migrating. Maybe the WordPress.com business model can be applied to Jekyll, with easy access to the nuts and bolts for advanced users..?\n"
    } ,
  
    {
      "tags"     : "Wordpress, Jekyll, Migration",
      "title"    : "This blog has migrated to Jekyll!",
      "excerpt"  : "You are now reading these words from a Jekyll-powered site, not Wordpress! But what does that actually mean?\n",
      "url"      : "/blog-has-moved-from-wordpress-to-jekyll/",
      "date"     : "Feb 14, 2022",
      "content"  : "You are now reading these words from a Jekyll-powered site, not Wordpress! But what does that actually mean?\n\nWell, I’ll be covering Why I Switched, How I Switched, and a few more detailed topics soon, but essentially the site is now:\n\n  Much faster\n  Much cleaner\n  Much easier to work with\n  Free to run!\n\n\nSpeed\n\nI compared some “before” and “after” scenarios, to see how much faster the speedy new site is:\n\n\n  \n    \n      Page\n      Wordpress\n      Jekyll\n      Comment\n    \n  \n  \n    \n      Homepage\n      3.58s to load, 44 requests\n      0.07s to load, 16 requests\n      A 98% decrease in load times(!), and 64% decrease in requests! The downside is larger images, discussed below.\n    \n    \n      Image heavy post\n      3.47s to load, 76 requests\n      0.08s to load, 21 requests\n      Another 98% load time decrease, and 72% request decrease. The image downside is very noticeable here, with over 4x as much data transferred.\n    \n    \n      Code heavy post\n      4.43s to load, 70 requests\n      0.08s to load, 13 requests\n      98% load decrease and 81% request decrease. The “image scaling” handicap isn’t relevant here, and the real speed difference comes into play!\n    \n  \n\n\nAll requests are from the live site, via Cloudflare, skipping local cache. Repeated 3x, middle value taken.\n\nSince the newer site is essentially all prerendered pages displayed when requested, it’s drastically faster. It’s also much, much simpler. However, you might have noticed in the above screenshots that the new site actually often transfers more data. For a streamlined, simple site, this would seem bizarre, until you look at the requests being made.\n\nThe new site only has 1 copy of every image. If I’ve been silly and used a giant screenshot as the post header, that’s the only size available! Previously, Wordpress would have a few copies of every image, and show the appropriate size. Once I’ve implemented this to the new site, speeds should improve slightly, and page size too.\n\n2022-02-16 update: Thumbnails are now implemented, we’re no longer loading the full image!\n\nAppearance\n\n\n  \n    \n      Page\n      Wordpress\n      Jekyll\n      Comment\n    \n  \n  \n    \n      Homepage\n      \n      \n      The Wordpress site had far too much going on. Whilst I do like the compact post previews, I prefer the visually striking banners on Jekyll.Since my blog is all about content, stripping everything else away seemed the best approach!\n    \n    \n      Post\n      \n      \n      The post page has improved more than the homepage. Code samples are now far more readable (they’re the point of the blog…), and the content of articles is the focus.For less code-based articles (example), the differences are even more noticeable. That being said, there’s still some tidying to do.\n    \n  \n\n\nWriting &amp; Maintaining\n\nPreviously when writing a post I had to stay online, and use the Wordpress WYSIWYG editor. This was OK for simple formatting like bold text, but I would often need to preview the actual post. This preview took up to 10 seconds to load.\n\nNow, I can write posts anywhere, using the syntax I’m most comfortable with, and can pick from a variety of offline clients with live preview etc (currently VSCode). I’m still figuring out the “drafts” process (hence this post!), but since it all runs on Git it should be fine!\n\nAdditionally, since the posts and site files are all essentially plain text, I can search &amp; update them all very easily. This is so, so much nicer than trying to navigate a clunky web interface, especially when making changes to the site’s structure / code. For comparison, just loading my Wordpress dashboard took 6-7 seconds. A full rebuild of the Jekyll site takes ~5 seconds, with subsequent builds taking 1-2 seconds.\n\nCost\n\nPreviously I was paying $8.99/mo to host this site via BlueHost.\n\nI am now paying $0, thanks to GitHub Pages. A tiny bit cheaper.\n\nConclusion\n\nWhilst the blog is now migrated, there’s a TON of cool things I now have the ability to do! Keep an eye out for future Jekyll-related posts…\n"
    } ,
  
    {
      "tags"     : "Kotlin, Room, SQLite, Migration",
      "title"    : "How to extract a Room list column into a new linked table, migrating data",
      "excerpt"  : "On a project recently the Room database consisted of a single table with many fields, some of which were Lists. This was fine, and easy to work with until… it wasn’t. We started seeing an error in Crashlytics caused by certain columns exceeding size limits. Uh oh.\n",
      "url"      : "/how-to-extract-a-room-list-column-into-a-new-linked-table-migrating-data/",
      "date"     : "Jan 12, 2022",
      "content"  : "On a project recently the Room database consisted of a single table with many fields, some of which were Lists. This was fine, and easy to work with until… it wasn’t. We started seeing an error in Crashlytics caused by certain columns exceeding size limits. Uh oh.\n\nThe solution was obvious: The biggest column needs to be split out into a new table. Actually doing this however, is a bit trickier…\n\nThe end result of this tutorial is available as a GitHub gist, it may be helpful to have it open as you proceed through the steps.\n\nThe problem\n\nTo summarise the problem using a simplified Car example:\n\n\n  We have an app with a single Car table in Room, with many columns.\n  One of these columns is a List&lt;Component&gt;, containing all the components in the car.\n  When serialised, this column is waaaay too big!\n  We need to extract this data into a new Component table, and link it to our Car.\n\n\nOur Database.kt is nothing unusual, and here’s how our Car.kt starts off looking:\n\n@Entity(tableName = \"Cars\")\ndata class Car(\n    @PrimaryKey\n    @ColumnInfo(name = \"id\")\n    val id: String,\n    \n    @ColumnInfo(name = \"colour\")\n    val colour: String,\n    \n    @ColumnInfo(name = \"components\")\n    val components: List&lt;Component&gt;\n)\n\n\nWhilst our Component.kt looks like (vastly simplified!):\n\ndata class Component(\n    val id: String,\n    val type: String,\n    val description: String,\n    val created: Long\n)\n\n\nThe solution\n\nSo, how are we going to do it?\n\n\n  Set up a new Component table.\n  Link the Components to our Cars.\n  Migrate our data:\n    \n      Prepare the database schema changes.\n      Fetch the existing Components and manipulate them.\n      Store these Components in our new format.\n      Tie it all together!\n    \n  \n\n\nStep 1: Creating a Component table\n\nThe simplest step, just need to add a few annotations as per the docs! Our Component is now:\n\n@Entity(tableName = \"Component\")\ndata class Component(\n    @PrimaryKey\n    @ColumnInfo(name = \"componentId\")\n    val componentId: String,\n    \n    @ColumnInfo(name = \"type\")\n    val type: String,\n    \n    @ColumnInfo(name = \"description\")\n    val description: String,\n    \n    @ColumnInfo(name = \"created\")\n    val created: Long\n)\n\n\nWe also need to make sure our database knows about this new table, and increment our version:\n\n@Database(\n    entities = [CarMetadata::class, Component::class],\n    version = 2\n)\ninternal abstract class CarDatabase : RoomDatabase() {\n\n\nStep 2: Linking Component to Car\n\nFirst, we need to make sure our Component can have a reference to a Car, via a new indexed carId column:\n\n@ColumnInfo(name = \"carId\", index = true)\nval carId: String,\n\n\nNext comes the tricky bit, defining our one-to-many relationship between Car and Component. The easiest way to do this, again as per the docs, is to convert Car into a CarMetadata entity, and create a new Car containing our columns as @Embedded or @Relation fields.\n\nThis will result in the following Car.kt:\n\nclass Car(\n    @Embedded\n    val metadata: CarMetadata,\n\n    @Relation(\n        parentColumn = \"id\", // The name of the CarMetadata ID field\n        entityColumn = \"carId\" // The name of the Component's car ID field\n    )\n    var components: List&lt;Component&gt;\n)\n\n\nAnd our CarMetadata.kt looks similar to how Car did before, except without components (as they are handled by the new Car)\n\n@Entity(tableName = \"Cars\")\ndata class CarMetadata(\n    @PrimaryKey\n    @ColumnInfo(name = \"id\")\n    val id: String,\n    \n    @ColumnInfo(name = \"colour\")\n    val colour: String\n)\n\n\nComponent also needs to define its link to CarMetadata:\n\n@Entity(\n    tableName = \"Component\",\n    foreignKeys = [ForeignKey(\n        entity = CarMetadata::class,\n        parentColumns = arrayOf(\"id\"), // The name of the CarMetadata ID field\n        childColumns = arrayOf(\"carId\"), // The name of the Component's car ID field\n        onDelete = ForeignKey.CASCADE\n    )]\n)\ndata class Component(\n\n\nStep 3.1: Preparing the database schema changes\n\nSo, we now have our new database schema set up, we’re done right? Well.. not quite. We need to migrate existing users! There’s 2 parts to this, migrating the database schema, and migrating the data itself.\n\nOur changes are too complex for Room’s automigrations, but we can use that to get us started. To generate an automigration script (using Room 2.4.0-alpha01 or above):\n\n\n  Build the app with our old schema, and version = 1.\n  Add automigrations = [AutoMigration(from = 1, to = 2)] into the @Database annotation.\n  Build the app with our new schema, and version = 2.\n  You should now be able to open a Room generated CarDatabase_AutoMigration_1_2_Impl.java file, containing Room’s best guess at migration.\n\n\nThis migration script contains 2 main parts:\n\n\n  A block of SQL to remove our components. Due to SQLite limitations, Room actually creates a new table without the column, transfers the data, then deletes the old one!\n  A block of SQL to create our new Component table, complete with foreign key link to Car, indexes, etc.\n\n\nWe are going to use this as the basis of our manual migration. In our CarDatabase.kt, we need to declare our migration when we build the database:\n\nRoom.databaseBuilder(context.applicationContext, CarDatabase::class.java, \"car_database\")\n    .addMigrations(MIGRATION_1_2)\n    .build()\n\n\nThe MIGRATION_1_2 is an object extending Migration, containing our custom migration:\n\nprivate val MIGRATION_1_2 = object : Migration(1, 2) {\n    override fun migrate(database: SupportSQLiteDatabase) {\n        // Our code from above goes here!\n    }\n}\n\n\nOur database is now being migrated, and we have control over the process! Next step, making sure user data survives the trip…\n\nStep 3.2: Parsing the existing data\n\nBefore we remove our components column, we need to pull all of the existing data out of it.\n\nTo do this, we’re going to:\n\n\n  Fetch every Car‘s id and its serialised List&lt;Component&gt;.\n  Parse this serialised data back into useful objects.\n  Update every Component‘s carId so it is linked with the Car.\n  Return this list of updated Components.\n\n\nWe’ll extract most of this complexity into a cursorToComponents function, called via:\n\noverride fun migrate(database: SupportSQLiteDatabase) {\n    val cursor = database.query(\"SELECT `id`, `components` FROM `Cars`\")\n    val components = cursorToComponents(cursor)\n\n\nThis function is fairly straightforward, hopefully the comments help:\n\nprivate fun cursorToComponents(cursor: Cursor): List&lt;Component&gt; {\n    // 1: First get the creation IDs and serialized component lists until there are no more rows\n    val carData = arrayListOf&lt;Pair&lt;String, String&gt;&gt;()\n    if (cursor.moveToFirst()) {\n        val carIdIndex = cursor.getColumnIndex(\"id\")\n        val componentsIndex = cursor.getColumnIndex(\"components\")\n        do {\n            carData.add(Pair(\n                cursor.getString(carIdIndex),\n                cursor.getString(componentsIndex)\n            ))\n        } while (cursor.moveToNext())\n    }\n\n    // 2: Parse each serialised list of components into objects, and update their carId\n    val componentsList = carData.flatMap { carIdAndComponents -&gt;\n        ComponentTypeConverter.toComponents(carAndComponents.second).onEach {\n            // 3: Update all carIds\n            it.creationId = carIdAndComponents.first\n        }\n    }\n\n    // 4: Return the list of components\n    return componentsList\n}\n\n\nIt’s worth mentioning this ComponentTypeConverter is a TypeAdapter, whatever was previously used to store the List&lt;Component&gt; can be reused. The bare minimum needed is:\n\n@TypeConverter\n@JvmStatic\nfun toComponents(jsonComponents: String): List&lt;Component&gt; {\n    val componentsType = object : TypeToken&lt;List&lt;Component&gt;&gt;() {}.type\n    return Gson().fromJson&lt;List&lt;Component&gt;&gt;(jsonComponents, componentsType)\n}\n\n\nStep 3.3: Storing the updated data\n\nWe’re nearly there! After step 3.2, we have a list of updated components. Once the schema changes in step 3.1 are performed, we can add our data back in.\n\nTo do this, we’re unfortunately going to need to manually write some SQL for an insertComponents function. We can make this a bit easier, and much safer, by using prepared statements:\n\nprivate fun insertComponents(database: SupportSQLiteDatabase, components: List&lt;Component&gt;) {\n    val insertSql = \"INSERT INTO \" +\n            \"Component(carId, componentId, type, description, created) \" +\n            \"VALUES (?, ?, ?, ?, ?)\"\n    val insertStatement = database.compileStatement(insertSql)\n    components.forEach { \n        insertStatement.clearBindings()\n        insertStatement.bindString(1, it.carId)\n        insertStatement.bindString(2, it.componentId)\n        insertStatement.bindString(3, it.type)\n        insertStatement.bindString(4, it.description)\n        insertStatement.bindString(5, it.created)\n        insertStatement.executeInsert()\n    }\n}\n\n\nAs you can see, the SQL isn’t at all complex, we’re just looping through every component object and inserting it in our updated database.\n\nStep 3.4: Putting the pieces together\n\nAll the pieces of the puzzle are now complete! The final step is putting them all in the migration script, in the correct order.\n\nAs mentioned previously, we need to pull the existing data, update the schema, then insert our updated data. I also wrapped a try/catch around it, just in case:\n\n        private val MIGRATION_1_2 = object : Migration(1, 12) {\n            override fun migrate(database: SupportSQLiteDatabase) {\n                try {\n                    // Extract existing components\n                    val cursor = database.query(\"SELECT `id`, `components` FROM `Cars`\")\n                    val components = cursorToComponents(cursor)\n\n                    // Make new table without components column, SQLite cannot delete columns\n                    database.execSQL(\"CREATE TABLE IF NOT EXISTS `_new_Cars` ...\")\n                    database.execSQL(\"INSERT INTO `_new_Cars` ...\")\n                    database.execSQL(\"DROP TABLE `Cars`\")\n                    database.execSQL(\"ALTER TABLE `_new_Cars` RENAME TO `Cars`\")\n\n                    // Add new table &amp; index\n                    database.execSQL(\"CREATE TABLE IF NOT EXISTS `component` ...\")\n                    database.execSQL(\"CREATE INDEX IF NOT EXISTS `index_component_carId` ...\")\n\n                    // Insert new components\n                    insertComponents(database, components)\n                } catch (e: Exception) {\n                    // Migration failed, Room will automatically roll back the transaction and retry when DB accessed\n                }\n            }\n        }\n\n\nSummary\n\nYou’re done! Of course, there’ll likely be some minor issues here and there before it all works flawlessly, and the following section should help with that.\n\nOverall, whilst this solution isn’t as neat as it could be, I’m pretty happy that it works! I wasn’t sure if this migration was possible initially, and hopefully this guide saves others the same trial and error that I did.\n\nIf this “extract column into table” process is a regular occurrence there are many potential improvements, such as:\n\n\n  Better error handling for the entire process, besides a blind try/catch.\n  A “Please wait, updating” screen to avoid any user interactions during this process.\n  Performing this upgrade as a WorkManager task silently in the background.\n  Tidying up the code in general, as it’s still fairly “proof of concept”.\n\n\nThe finished files are available as a GitHub gist, seeing an overview may help. Good luck!\n\nPotential issues\n\nUpdating existing codebase\n\nOf course, these changes will break some existing code. Most are easy to fix, here’s a summary:\n\n\n  Make sure you update every instance where Components are created to now have a carId, otherwise they will become orphaned in the database.\n  Every call to car.type etc will now need to use car.metadata.type.\n\n\nType adapters\n\nYour Component class may have lots of custom objects. As these are now being stored in columns, instead of serialised, Room needs to know how to save and load them.\n\nThe Gist has an example of using Gson to parse complex data, but the Android documentation also shows how to convert simpler formats.\n\nOnce your type adapters are set up, you can use them when manually saving data too, e.g.:\n\ninsertStatement.bindString(17, BackgroundTypeConverter.fromBackground(it.background))\n\n\nStoring booleans\n\nRoom actually stores booleans (and ints) as longs. Because of this, you will need to convert them yourself when saving the data.\n\nSince true = 1 and false = 0, this works for boolean conversion:\n\ninsertStatement.bindLong(10, if (it.isLocked) 1 else 0)\n\n\nYou may also encounter some issues with null data types, so make sure none of the prepared statement use nullable data.\n\nStoring sealed classes\n\nI had some issues storing a sealed class (one still unresolved), and ended up needing to register subtypes on my Gson instance.\n\nSimilarly, I had issues with needing to serialise the type of a sealed class, luckily fairly easily resolved.\n\nDebugging\n\nIt’s really, really, really important to test this migration extremely carefully. I’d recommend inspecting your Room database before and after migration multiple times, with every possible combination of your data.\n\nTransactions &amp; time\n\nOne bit that initially tripped me up is the migration will only be performed the first time the database is accessed, not on app startup.\n\nThe migration process was relatively quick, with &lt;10ms to parse &amp; insert each Component meaning a total time of 1-2s. Your time will obviously depend on the data size and complexity, but this approach’s speed seems OK for up to 100-200 rows.\n\nVarious comments online indicate Room executes migrations in a transaction, however I’m not certain. Assuming this is true, this means any failed migration will automatically rollback, and be tried again the next time the database is accessed.\n\nFurther reading / references\n\n\n  Full Gist of the solution: https://gist.github.com/JakeSteam/831c9ea7962f923a01d451e650918031\n  General Room info: https://developer.android.com/training/data-storage/room\n  Configuring Room one-to-many relationships: https://developer.android.com/training/data-storage/room/relationships#one-to-many\n  Room automigrations: https://developer.android.com/training/data-storage/room/migrating-db-versions#automated\n  Using type converters: https://developer.android.com/training/data-storage/room/referencing-data#type-converters\n  Inspecting your Room database: https://developer.android.com/studio/inspect/database#open\n  Creating prepared statements: https://stackoverflow.com/a/29797229/608312\n  Fetching data from a SQLite database: https://stackoverflow.com/a/56978555/608312\n\n"
    } ,
  
    {
      "tags"     : "Android, Gradle, kapt, Kotlin, Merge",
      "title"    : "Fixing a misleading \"duplicate class\" error during kaptDebugKotlin after merging",
      "excerpt"  : "Recently, I merged a repository’s main branch into an older feature branch, only to get a mysterious InvocationTargetException during compilation:\n",
      "url"      : "/fixing-a-misleading-duplicate-class-error-during-kaptdebugkotlin-after-merging/",
      "date"     : "Oct 13, 2021",
      "content"  : "Recently, I merged a repository’s main branch into an older feature branch, only to get a mysterious InvocationTargetException during compilation:\n\n\n\nViewing the full error (by clicking “Build: failed”) provided lots more information but… only deepened the mystery! All of the apparently duplicate classes are temporary Java files (the codebase is 100% Kotlin) and the classes all only have 1 definition.\n\nThere’s also various errors to do with “ANTLR Tool version”, and even some lint warnings about deprecated methods sneaking in. Definitely important, but very unrelated to the duplicate class mystery. My first thought was Android Studio’s cache causing issues, but a project clean and cache clear didn’t help. Hmm!\n\n\n\nAfter looking into all of the Kotlin files, checking no major changes had been merged, redoing the merge, and fruitlessly searching various StackOverflow answers, I finally found the answer.\n\nThe merge had resulted in a class (that referenced all the supposedly duplicate classes) having two companion objects:\n\n\n\nThe obvious fix of removing the outdated companion immediately resolved the issue, shame the original error was so unhelpful!\n\nAnd yes, this did take an embarrassingly long time to resolve.\n"
    } ,
  
    {
      "tags"     : "Android, Locale, Localisation, Strings",
      "title"    : "A quirk of strings.xml for multiple regions per language in Android",
      "excerpt"  : "Recently a colleague and I worked on an issue where a displayed URL was intended for another region entirely, but all the strings were seemingly in the correct XMLs. This was… very odd, yet the eventual solution does make sense!\n",
      "url"      : "/a-quirk-of-strings-xml-for-multiple-regions-per-language-in-android/",
      "date"     : "Sep 16, 2021",
      "content"  : "Recently a colleague and I worked on an issue where a displayed URL was intended for another region entirely, but all the strings were seemingly in the correct XMLs. This was… very odd, yet the eventual solution does make sense!\n\n\n  The app exists in a single market, e.g. the UK, which has all URLs etc in values/strings.xml. They display fine.\n  The app expands into a non-English market, e.g. France, and has all new strings in /values-fr/strings.xml. They display fine.\n  The app expands into another English market, e.g. Ireland, and has a few new strings in /values-en-rIE/strings.xml. They display fine.\n  Uh oh, the app’s URLs in the original market, the UK, have been replaced by Irish strings (see banner)!\n\n\nOur first clue was the issue didn’t occur on our emulators (set to default en-US), but did apply on our physical devices. Our next clue was strings in /values-en-rGB/strings.xml that duplicated /values/strings.xml.\n\nThe problem was the physical device’s locale being en-rGB. When Android tried to find the most relevant strings, it found en-rIE. This was the correct language, so it used those! This highlighted a faulty assumption: That a strings file for a specific region will only be used for that region. Instead, if Android cannot find a better match, a region’s strings will be used for any region in that language.\n\nThe solution was that second clue from earlier: If defining region-specific strings, make sure they are all defined for all regions, or there is one for the language itself!\n\nBelow is a screenshot of the final setup, there’s also a proof of concept repository:\n\n\n\nFurther reading / resources:\n\n\n  “Language and locale resolution overview” on Android Developers\n  “How Android finds the best-matching resource” on Android Developers\n\n"
    } ,
  
    {
      "tags"     : "Branch, Git, GitHub, PR",
      "title"    : "Don't revert merges! A story of a mystery pull request merge",
      "excerpt"  : "A Friday afternoon, after work hours. You and a colleague are merging the final few pull requests before giving a build to weekend testers. (Update July 2023: GitHub has improved the behaviour for this scenario!)\n",
      "url"      : "/dont-revert-merges/",
      "date"     : "Aug 7, 2021",
      "content"  : "A Friday afternoon, after work hours. You and a colleague are merging the final few pull requests before giving a build to weekend testers. (Update July 2023: GitHub has improved the behaviour for this scenario!)\n\nYou agree the “small feature” PR can be merged, but the unrelated “unfinished big feature” PR still needs some work next week. No problem. The “small feature” PR is merged, the build is made. Great.\n\nYou quickly double check next week’s changes required for “unfinished big feature” and… it’s been merged into develop!? 5 minutes ago!? What on earth…\n\nThe mystery merge\n\nThe prelude above is exactly what happened to me yesterday! My colleague merged the small feature, and according to GitHub they merged the big unfinished feature too.\n\nWe had a very confusing conversation to work out what had happened, with the following basic facts:\n\n\n  A small, finished PR was merged, as intended.\n  A large, unfinished PR was also merged, with no explicit action.\n  The small, finished PR had a bit of a messy git history, but the code changes were fine.\n\n\nHere’s a “proof of concept” recreation of the mystery merge, feel free to try and work it out yourself before reading on: https://github.com/JakeSteam/github-merge-mystery-poc/pull/2\n\nExplanation\n\nSo, what happened? Looking at a recreation of the “small, finished feature” PR may help, here’s the chain of relevant events:\n\n\n  Big feature PR is raised, changes are suggested.\n  Dev working on small feature PR accidentally merges in the big feature branch when pulling due to similar ticket numbers, but immediately reverts it.\n  The small feature PR is merged in. Every single commit from big feature PR is included, with a revert commit at the end.\n  GitHub notices every commit in big feature PR is now merged in (technically), so closes the PR. This is attributed to whoever merged the small PR!\n\n\nThe git branch graph shows these events:\n\n\n\nNow it becomes obvious that all of big feature (branchB)’s commits are merged into small feature (branchA), but none of the code remains!\n\nBecause of this, closing the pull request is a reasonable thing for GitHub to do. Otherwise the eventual merge might actually do nothing, leading to the code never being included in the main branch (because it was reverted in branchA).\n\nConclusion\n\nWhen looking at the commits on a fresh repo, this explanation might have seemed immediately obvious. However, if you’re in a larger team, with other pull requests being merged and created between these two, it definitely isn’t as clear! Additionally, this merge &amp; revert may have happened days/weeks ago, with many commits since.\n\nThe part I find particularly concerning is how difficult it is to trace this. The issue is hidden if you aren’t specifically looking for a merge and revert.\n\nThe automatically closed PR should absolutely say WHY it has been closed. Currently, the person who accidentally did the revert and merge isn’t mentioned at all, instead the merger of the branch is “blamed”, and the unusual events aren’t flagged anywhere. Additionally, the person who unintentionally closed this PR isn’t notified that their merge has had side-effects, so this could result in lost work. It’s very easy to imagine a situation where the author of the automatically closed PR sees their PR has been “merged”, and assumes their work is now, well, merged.\n\nThe potential for losing work or not knowing the status of code is definitely in this albeit niche situation.\n\nUpdate: GitHub now shows a merge reason in this scenario!\n\nRecommendations\n\nHere’s a couple of ways to avoid this happening, or at least catch the issue:\n\n\n  Squash commits when merging. This is a team preference thing, and we actually usually do, but in this case didn’t.\n  Don’t accidentally merge other branches. Obviously this would avoid the whole problem, but mistakes happen!\n  If a git mistake isn’t pushed, hard reset to before the mistake instead of reverting.\n  Review pull requests commit by commit. I definitely don’t do this, but I do skim the commit titles, I’ll keep an eye out for merge &amp; reverts after this!\n  Talk if something strange happens. We caught this issue immediately because the merge didn’t make sense. Questioning an unexpected merge of your PR is always OK.\n  Finally, GitHub could provide a more helpful pull request closing message. Instead of “Jake merged commit abc123 into main”, it could say “Pull request automatically closed as all commits are on main (Jake merged commit abc123)”.\n\n"
    } ,
  
    {
      "tags"     : "Android, DiffUtil, GridLayoutManager, MVVM, RecyclerView",
      "title"    : "Creating a MVVM RecyclerView grid with quick drag and drop item swapping, Room / LiveData support, and more!",
      "excerpt"  : "As part of my current project BocaBase, I needed a grid of items that could be swapped around easily. Whilst there were a few answers on StackOverflow, most of them resulted in flickering animations, didn’t work with Room / LiveData / MVVM, or were awful to use!\n",
      "url"      : "/creating-a-mvvm-recyclerview-grid-with-quick-drag-and-drop-item-swapping-room-livedata-support-and-more/",
      "date"     : "Jul 12, 2021",
      "content"  : "As part of my current project BocaBase, I needed a grid of items that could be swapped around easily. Whilst there were a few answers on StackOverflow, most of them resulted in flickering animations, didn’t work with Room / LiveData / MVVM, or were awful to use!\n\nOne of the biggest challenges is moving items when the items are loaded and sorted from a database. They must have their ordering changed in the database, moved within the RecyclerView’s adapter, AND visually be moved.\n\nWhilst the solution in this post definitely isn’t perfect, it’s much better than snippets I could find already. There’s a video preview below, and a full Gist of the solution is available, this post is mostly to point out the interesting parts of it.\n\n\nNote: The video also contains “merging” items together, which isn’t included in this tutorial.\n\nXML (table_fragment.xml)\n\nA RecyclerView with a GridLayoutManager is used to let us use more up-to-date Android technology. The important attributes are:\n\n\n  app:layoutManager=\"androidx.recyclerview.widget.GridLayoutManager\": Use a grid instead of simple list.\n  app:spanCount=\"5\": Use a 5 column grid.\n  android:overScrollMode=\"never\": Disables the “overscroll” animations (the semi-circles of colour when you reach the start / end of a RecyclerView).\n\n\n&lt;androidx.recyclerview.widget.RecyclerView\n    android:id=\"@+id/itemGrid\"\n    android:layout_width=\"0dp\"\n    android:layout_height=\"0dp\"\n    android:layout_marginVertical=\"8dp\"\n    android:overScrollMode=\"never\"\n    app:layoutManager=\"androidx.recyclerview.widget.GridLayoutManager\"\n    app:layout_constraintBottom_toTopOf=\"@id/testButton\"\n    app:layout_constraintEnd_toEndOf=\"parent\"\n    app:layout_constraintStart_toStartOf=\"parent\"\n    app:layout_constraintTop_toBottomOf=\"@id/reputation\"\n    app:spanCount=\"5\"\n    tools:listitem=\"@layout/board_item\" /&gt;\n\n\nFragment (TableFragment.kt)\n\nThe fragment just sets up the adapter and RecyclerView, and observes a items LiveData from the ViewModel. The important parts are:\n\n\n  viewModel.items.observe ... setItems: Updates the UI if the grid items change for a non-drag and drop reason, and handles initial load.\n  ItemAdapter( ... ): We pass in a reference to the ViewModel’s item click and item save functions, so the adapter can call them directly\n  adapter.itemTouchHelper.attachToRecyclerView: Adds the touch listener that we’ll set up later.\n  setHasFixedSize(true): Lets the RecyclerView optimise for a fixed length of content.\n\n\nclass TableFragment : Fragment() {\n\n    private var binding: TableFragmentBinding by autoCleared()\n    private val viewModel: TableViewModel by viewModels()\n    private lateinit var adapter: ItemAdapter\n\n    override fun onCreateView(\n        inflater: LayoutInflater, container: ViewGroup?,\n        savedInstanceState: Bundle?\n    ): View {\n        binding = TableFragmentBinding.inflate(inflater, container, false)\n        binding.viewModel = viewModel\n        binding.lifecycleOwner = viewLifecycleOwner\n        return binding.root\n    }\n\n    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {\n        super.onViewCreafted(view, savedInstanceState)\n        setupRecyclerView()\n\n        viewModel.items.observe(viewLifecycleOwner) {\n            adapter.setItems(it)\n        }\n    }\n\n    private fun setupRecyclerView() {\n        adapter = ItemAdapter(\n            viewModel::handleItemClick,\n            viewModel::saveItems\n        )\n        adapter.itemTouchHelper.attachToRecyclerView(binding.itemGrid)\n        binding.itemGrid.setHasFixedSize(true)\n        binding.itemGrid.adapter = adapter\n    }\n\n}\n\n\nViewModel (TableViewModel.kt)\n\nThe ViewModel usually does most of the work, but in this example the adapter handles almost all of it. As such, it just needs the callbacks we passed to the adapter.\n\n    fun handleItemClick(ownedItem: OwnedItem) {\n        _textToShow.postValue(String.format(\"That's a %s at position %d!\", ownedItem.item.name, ownedItem.position))\n    }\n\n    fun saveItems(items: List) {\n        viewModelScope.launch(Dispatchers.IO) {\n            itemRepository.insertItems(items)\n        }\n    }\n\n\nAdapter (ItemAdapter.kt)\n\nThe Adapter is very simple, but quite lengthy due to using DiffUtil and ItemTouchHelper (covered next). It’s pretty much just a bare-bones adapter:\n\nclass ItemAdapter(\n    private val itemClickListener: (OwnedItem) -&gt; Unit,\n    private val itemSaver: (List) -&gt; Unit\n) : RecyclerView.Adapter() {\n\n    val items = ArrayList()\n\n    fun setItems(newItems: List) {\n        val result = calculateDiff(newItems)\n        items.clear()\n        items.addAll(newItems)\n        result.dispatchUpdatesTo(this) // See DiffUtil later in this post\n    }\n\n    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {\n        val binding: BoardItemBinding =\n            BoardItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)\n        return ItemViewHolder(binding, itemClickListener, itemTouchHelper::startDrag)\n    }\n\n    override fun getItemCount(): Int = items.size\n\n    override fun onBindViewHolder(holder: ItemViewHolder, position: Int) =\n        holder.bind(items[position])\n\n}\n\n\nViewHolder (inside ItemAdapter.kt)\n\nThe ViewHolder is why we needed item touch and click listeners earlier! The touch listener triggers the drag as soon as you put your finger down on the item, which makes moving items much easier.\n\nclass ItemViewHolder(\n    private val itemBinding: BoardItemBinding,\n    private val itemClickListener: (OwnedItem) -&gt; Unit,\n    private val itemTouchListener: (ItemViewHolder) -&gt; Unit\n) : RecyclerView.ViewHolder(itemBinding.root) {\n\n    private lateinit var ownedItem: OwnedItem\n\n    fun bind(ownedItem: OwnedItem) {\n        this.ownedItem = ownedItem\n        Glide.with(itemBinding.root).load(ownedItem.item.image).into(itemBinding.image)\n        if (ownedItem.item != Item.NONE) {\n            itemBinding.root.setOnTouchListener { v, event -&gt;\n                if (event.actionMasked == MotionEvent.ACTION_DOWN) {\n                    itemTouchListener.invoke(this)\n                }\n                false\n            }\n            itemBinding.root.setOnClickListener {\n                itemClickListener.invoke(ownedItem)\n            }\n            itemBinding.tier.text = \"Pos: ${ownedItem.position}\"\n        } else {\n            itemBinding.tier.text = \"\"\n        }\n    }\n\n}\n\n\nDiffUtil (inside ItemAdapter.kt)\n\nUsing a DiffUtil essentially enables clever animations when data changes, just by telling it how to compare items! Nothing unique here, the code will be very similar to all other DiffUtils.\n\n    private fun calculateDiff(newItems: List) = DiffUtil.calculateDiff(object : DiffUtil.Callback() {\n\n        override fun getOldListSize() = items.size\n\n        override fun getNewListSize() = newItems.size\n\n        override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {\n            return items[oldItemPosition] == newItems[newItemPosition]\n        }\n\n        override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {\n            val newProduct = newItems[newItemPosition]\n            val oldProduct = items[oldItemPosition]\n            return newProduct.id == oldProduct.id\n                    &amp;&amp; newProduct.item == oldProduct.item\n                    &amp;&amp; newProduct.board == oldProduct.board\n                    &amp;&amp; newProduct.position == oldProduct.position\n        }\n    })\n\n\nItemTouchHelper (inside ItemAdapter.kt)\n\nThis is probably the most complicated part of the entire setup, since it handles the actual swapping.\n\nonMove is triggered as you drag an item over another, hence why we update the newPosition. Similarly, oldPosition is updated inside onSelectedChanged when the item is “picked up”.\n\nThese two positions are then “swapped” when the item is “dropped” (ACTION_STATE_IDLE), with the following steps:\n\n\n  Get the old and new object to be swapped.\n  Set their internal positions to each other (so that when the data is reloaded from database it will be ordered correctly).\n  Swap their positions within the adapter’s list of items (so that the adapter is currently correct).\n  Save the items from step 2 (this itemSaver is the viewModel::saveItems passed inside the adapter constructor, that inserts them into the database!)\n\n\n    val itemTouchHelper = ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(\n        ItemTouchHelper.UP or ItemTouchHelper.DOWN or\n                ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT, 0\n    ) {\n        var oldPosition = -1\n        var newPosition = -1\n\n        override fun onMove(\n            recyclerView: RecyclerView,\n            viewHolder: RecyclerView.ViewHolder,\n            target: RecyclerView.ViewHolder\n        ): Boolean {\n            newPosition = target.adapterPosition\n            return false\n        }\n\n        override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {}\n\n        override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {\n            super.onSelectedChanged(viewHolder, actionState)\n            when (actionState) {\n                ItemTouchHelper.ACTION_STATE_DRAG -&gt; {\n                    viewHolder?.adapterPosition?.let { oldPosition = it }\n                }\n                ItemTouchHelper.ACTION_STATE_IDLE -&gt; {\n                    if (oldPosition != -1 &amp;&amp; newPosition != -1 &amp;&amp; oldPosition != newPosition) {\n                        val old = items[oldPosition] // Step 1\n                        val new = items[newPosition]\n\n                        old.position = newPosition // Step 2\n                        new.position = oldPosition\n                        items[oldPosition] = new // Step 3\n                        items[newPosition] = old\n\n                        itemSaver.invoke(listOf(old, new)) // Step 4\n                        notifyDataSetChanged()\n                        oldPosition = -1\n                        newPosition = -1\n                    }\n                }\n            }\n        }\n    })\n\n\nSummary\n\nThis is a bit of a weird post, since the code is essentially combining disparate StackOverflow answers into one useful whole. However, I struggled finding anything similar already existing, so this will hopefully save a few people many, many hours!\n\nThere’s also quite a few parts that I intend to improve upon. For example, it shouldn’t be necessary to call notifyDataSetChanged inside onSelectedChanged, since we know the exact positions changed. However, notifying just the changed items plays an unwanted and confusing animation that I couldn’t figure out how to disable. I’ll update this post when I inevitably decide to spend a few days deep diving RecyclerView animations, I’m not quite that far gone yet though..!\n\nIf you found this post helpful, please go upvote the StackOverflow questions &amp; answers below. They’re quite old, mostly in Java, and deserve far more attention.\n\nReferences\n\n\n  Basic RecyclerView info: https://developer.android.com/guide/topics/ui/layout/recyclerview\n  Core swapping functionality, albeit a quite buggy looking one: https://stackoverflow.com/a/62147429/608312\n  Dragging items immediately, instead of waiting for long press: https://stackoverflow.com/a/50058957/608312\n  Dragging items outside the RecyclerView’s bounds: https://stackoverflow.com/a/41071941/608312\n  Disabling RecyclerView’s scrolling animations: https://stackoverflow.com/a/27724949/608312\n  MVVM RecyclerView: https://medium.com/@ali.muzaffar/android-recyclerview-using-mvvm-and-databinding-d9c659236908\n\n"
    } ,
  
    {
      "tags"     : "Logitech, WFH, working from home",
      "title"    : "Improving my Windows & MacOS triple monitor working from home setup",
      "excerpt"  : "Like many others in the world, I’ve been working from home for just over a year now. I use my personal machine for Spotify / background TV during the workday, and I’ve ended up with a bizarre workflow that involves hopping between my personal Windows and work MacOS machine all day!\n",
      "url"      : "/improving-my-windows-macos-triple-monitor-working-from-home-setup/",
      "date"     : "Apr 26, 2021",
      "content"  : "Like many others in the world, I’ve been working from home for just over a year now. I use my personal machine for Spotify / background TV during the workday, and I’ve ended up with a bizarre workflow that involves hopping between my personal Windows and work MacOS machine all day!\n\nThis requires a few unique solutions, and recently I decided to spend a bit of money making this setup work properly. In this post I’ll cover the changes in case others are in a similarly odd setup.\n\nNote: None of the Amazon links in this article are referral links!\n\nBefore / After\n\nFirst, my absolutely awful previous setup. Beyond the immediately obvious cable chaos, here’s the main problems:\n\n  Two mice, two keyboards\n  Low monitors causing poor posture\n  Laptop blocking a significant portion of right screen\n  Bulky cable tray underneath desk occasionally getting nudged by legs\n\n\n\n  \n    \n      Overview\n      From above\n      Under\n    \n  \n  \n    \n      \n      \n      \n    \n  \n\n\nNext, my current setup. All of the above issues are now resolved completely, and hopefully the difference is immediately obvious! The changes are:\n\n  One mouse &amp; keyboard\n  Higher monitors leading to better posture\n  No screen blocking\n  No cable tray underneath\n  Few visible cables\n  Much more desk space, due to no stands\n\n\n\n  \n    \n      Overview\n      From above\n      Under\n    \n  \n  \n    \n      \n      \n      \n    \n  \n\n\nRequirements\n\nDue to my somewhat strange habit of using both Windows &amp; MacOS machines all day, choosing peripherals wasn’t as simple as usual. Instead, I had to prioritise cross compatibility and wireless capability. These were my requirements:\n\n\n  Keyboard and mouse must be capable of switching between machines instantly\n  All wires must be removed if possible\n  Monitors must be high off my desk (to avoid 16″ laptop screen)\n\n\nPeripherals\n\nKeyboard\n\nI previously had the Logitech G213, and it was… fine. A bit noisy to type on, and more intended for gaming than actual typing. Since typing is more of a priority for me now, I decided on a keyboard with laptop-y keys. Keys are of course personal preference, I often work with others in the room and simply prefer how laptop keys feel.\n\nDue to these factors, I went for the confusingly named Logitech MX Keys. It fit all of my criteria, being wireless, able to switch devices instantly, and laptop-style keys. It also has Logitech Flow, covered in the mouse section.\n\n\n\nAfter 2 weeks, it’s easily the best keyboard I’ve ever used, and everyday typing suddenly feels much easier than it has before. The cross-platform labelled keys are a nice touch, and help when my muscle memory gets confused by the multiple OS!\n\nMouse\n\nI previously used two Logitech G203 mice, and found them excellent. However, they were wired, meaning they were no longer suitable for my new setup!\n\nI instead went for the Logitech MX Master 3, mostly because it goes perfectly with the keyboard, and contains the same Logitech Flow technology. Essentially, Flow lets you seamlessly move &amp; copy/paste between up to 3 machines just by moving your mouse to the edge of the screen (and optionally pressing CTRL). Here’s a demo video.\n\n\n\nAfter a couple of weeks, I still feel like the mouse has a lot of potential I’m not using. For example there’s a disabled button on the thumb rest that can be used for gestures, and even a horizontal scroll wheel. Perhaps these will be useful one day! The vertical scrollwheel also deserves complimenting, the super smooth movement at high speeds means I find myself idly scrolling just for the feel.\n\nPhone charger\n\nI previously used a generic USB-C cable, along with a metal stand for my phone. As I’m an Android dev I often run development apps on my phone, hence not using wireless charging.\n\nHowever, after experimenting with ADB over WiFi a bit I realised I no longer needed to plug my phone in. Both my PC and Mac could easily connect to the device, freeing me up to use a wireless charger. I chose a fairly standard one, capable of fast charging and so far no complaints.\n\nController\n\nWhilst I don’t game as much as I used to, I do play a LOT of Forza. My 5 year old Xbox 360 controller was starting to show it’s age, with rubbed off joystick rubber, scratches, etc.\n\nConsumer choice is pretty limited here, especially as I wanted to stick with Xbox as I know the controls well. I bought the standard Xbox controller as it has bluetooth connectivity, then improved it with a rechargeable battery pack.\n\nHeadset\n\nThe only peripheral not changing! I’ve been using my Sony WH-1000XM3 headset for 12-16 hours a day for over 6 months now, and have only one complaint. Currently switching between machines is a manual process, it would be nice if it received an update for automatic switching like the XM4’s.\n\nOthers\n\nSince I now take video calls exclusively from my work laptop, I realised my Blue Yeti Nano microphone and webcam were no longer needed, so those have also been put away.\n\nMonitors\n\nI use 3x ElectriQ 27″ 1440p 95hz monitors. They’re often available cheaper from other sites, and are a rebranded Pixio PX275H. The Pixio is pretty well reviewed, and luckily the ElectriQ logo comes right off, leaving a clean black bezel. They’re great monitors, although the stand has little flexibility.\n\nI resolved this by buying two HUANUO monitor mounts, one with 2 arms and one with 1 arm. The initial setup can be time consuming, but they’re very cheap and work with most desks (either via clamp or drilling a hole). They also feature some very nice cable management, in my photos at the start the left monitor has zero visible cables. Additionally as they have a tuneable gas spring, the screen can be moved up or down with a single finger! Finally, the 2 arm variant has USB integrated so is used for my Logitech Unifying Receiver (keyboard &amp; mouse) and Bluetooth Receiver (controller &amp; headset).\n\nWhen mounting my 3 monitors, I chose to place them quite high. This was both to encourage good posture, and because I’m one of those people who sits on their leg, ruling out any chairs with arms!\n\nFull list\n\nWhilst a full list of all tech I use is available, here’s the items purchased as part of this revamp:\n\n\n  2 armed monitor stand: £44.99\n  1 armed monitor stand: £24.99\n  Logitech MX Keys: £90.38\n  Logitech MX Master 3: £94.99\n  Xbox Controller: £47.00\n  Xbox Battery Pack: £19.99\n  Wireless charger: £11.04\n  Total: £333.38\n\n\nConclusion\n\nWhilst spending £330 for no performance benefit might initially seem crazy, I would absolutely pay it again. Having a work environment that is conducive to actually getting things done can’t be overvalued.\n\nImproving my setup changed how I feel about my machine completely, and made everything much much smoother. It improved concentration at work, undoubtedly improved typing speed, and let me focus on the actual work!\n\nThat being said, there’s absolutely room for improvement:\n\n\n  Some monitor cables would ideally be slightly longer, letting them be completely obscured from view.\n  Ideally the laptop could be mounted somewhere, hiding the cables needed. For now, I still use it for the webcam.\n  The chair I use is very average, being a cheap IKEA one I’ve had for years!\n  I naturally go to very minimalist white/black, the area probably needs more colour &amp; personality..! The plants / bookcase behind help though.\n  Whilst the setup looks very clean from the front, the “behind the scenes” for all the monitor cables is… pretty rough!\n\n"
    } ,
  
    {
      "tags"     : "GitHub, markdown, pr, pull request, review",
      "title"    : "Creating the PR template that Future You wishes Past You used",
      "excerpt"  : "How many times have you found a confusing line of code, figured out which ticket it solved, opened the relevant PR and… nothing. There’s a few approvals and it’s merged, with no explanation / discussion of what on earth is going on!\n",
      "url"      : "/creating-a-pr-template/",
      "date"     : "Dec 1, 2020",
      "content"  : "How many times have you found a confusing line of code, figured out which ticket it solved, opened the relevant PR and… nothing. There’s a few approvals and it’s merged, with no explanation / discussion of what on earth is going on!\n\nWhen this happens, the only way to try and understand the code is to hope the author still works at the company (and remembers ancient, confusing code!). All it takes is a poor memory / high turnover, and there can easily be no helpful information anywhere.\n\nThis post will introduce a PR template I’ve used / refined through multiple teams, and have found extremely helpful. An example PR created using it is available in a sample repo.\n\nPS: I’m very sorry for the ridiculous title, I couldn’t resist.\n\nWhy use a pull request template?\n\n\n  As mentioned in the intro, it ensures all PRs have enough information to be useful for future developers.\n  A consistent format helps newer developers know what a PR entails, without having to ask.\n  It can remind a developer of a forgotten task, for example when they try to answer “What tests have been added?” and realise none have!\n  Finally, having a structure with distinct sections avoids any “walls of text” or unstructured PRs.\n\n\nHow do I setup a pull request template?\n\nThe actual location varies by code host, but the approach is always a markdown template within a specific folder:\n\n\n  GitHub (also has limited template support)\n  Azure DevOps (also supports per-branch templates!)\n  GitLab\n  BitBucket\n\n\nThe PR template\n\nThe PR template is provided in an example repository, here is the raw markdown, and here is an example PR raised with it.\n\n\n\nHere’s why each section is essential:\n\n“Tracked by…”\n\nHaving a link to the actual ticket makes it easy for developers to understand the purpose of the ticket, as well as ensuring information can easily be found.\n\nMake sure to change the URL to match your JIRA / other ticket system format.\n\n“This PR…”\n\nHaving a simple, one sentence summary of the ticket ensures the PR has a clear overall focus. For example, “This PR...\n\n\n  adds an email validator to the login screen”\n  fixes a bug caused by an invalid string reference”\n  disables the no longer supported Fabric integration”\n\n\n“Considerations and implementations”\n\nThis is the main body of the PR, and varies massively by PR. A simple PR may have a single sentence here, others may have multiple paragraphs, diagrams, etc.\n\n“How to test”\n\nHaving an ordered, straightforward list of steps to test the changes massively helps overall understanding. This list can also be used as hints for QA, and is a good place to upload any custom configuration files etc needed.\n\n“Test(s) added”\n\nHaving this section helps reminds developers to always add tests, or explain themselves if they can’t!\n\n“Screenshots”\n\nHaving this section makes visual changes immediately obvious, and means visual bugs can often be identified instantly. Also, the screenshots are useful for non-devs preparing content for sprint review, or signing off work.\n\nIt’s worth mentioning that in less visual projects, this section could be called “Changes” and contain logs / process flows / etc. This section sometimes contains screenshots of Charles network requests or LogCat messages as well as normal screenshots.\n\nConclusion\n\nAdding a PR template is a very easy change, yet drastically improves documentation quality. It’s the dream, writing self-organising documentation as you go! A template also ensures the repository contains its own documentation, instead of relying on employees knowing past tickets.\n\nSince the template provided will probably be customised over time according to how your team functions, a repo of example templates may be useful.\n\nWhilst having testing steps on the PR is useful for code review, ideally it should be accessible to QAs &amp; POs too. A basic way to do this is just put a link to the PR on the ticket when moving it to “Ready to test”, but I’m sure there are automated solutions!\n\nFinally, remember that if you’re using GitHub for PRs you also have access to the extremely useful rich diffs in PRs!\n"
    } ,
  
    {
      "tags"     : "App Links, Deep Links, GitHub, json",
      "title"    : "Associate Android app links with your subdomain using GitHub Pages & Cloudflare",
      "excerpt"  : "As part of my APOD wallpaper rewrite, I wanted to support universal links / app links. These allow users with the app installed to click a link like apod.jakelee.co.uk/day/2020-01-01 and be taken directly to that APOD within the app!\n",
      "url"      : "/associate-android-app-links-with-your-subdomain-using-github-pages-cloudflare/",
      "date"     : "Oct 21, 2020",
      "content"  : "As part of my APOD wallpaper rewrite, I wanted to support universal links / app links. These allow users with the app installed to click a link like apod.jakelee.co.uk/day/2020-01-01 and be taken directly to that APOD within the app!\n\nHowever, to complicate matters slightly my domain is behind Cloudflare, I wanted to use a subdomain, and I wanted to use GitHub pages for free hosting. This introduced a few problems, hopefully this post helps others solve them!\n\nAs a very brief overview of the process, we’ll be hosting a config file that tells Google / Android our app is allowed to automatically handle our links.\n\nStarting resources\n\nBefore we get started, I’d like to mention this extremely helpful URL I found whilst implementing app links. The response shows what Google uses when they try to validate your links, along with any errors encountered. To check your site, just replace apod.jakelee.co.uk with your URL (you can also look at Facebook’s or Google’s!).\n\nThroughout this tutorial we’ll also be using the “App Links Assistant”, available under “Tools” in Android Studio. There’s a very detailed companion guide, containing excellent information on handling the links and generating the asset linking file.\n\nI’d also recommend reading through the App Links training, specifically verifying links.\n\nPreparing your JSON linking file\n\nFirst, to tell Android that our app is allowed to handle certain URLs, we need to host an assetlinks.json file. This essentially lists our URL, our app’s package, and our app’s signature.\n\nThis can be made manually, but Android Studio’s wizard (Tools -&gt; App Links Assistant -&gt; Associate website) is much easier.\n\nSimply enter your domain and package, along with your signing information (to retrieve the certificate), and the file will be made for you. Save it somewhere, and we’ll move on to hosting it.\n\n\n\nMaking a GitHub pages repository\n\nNext, we need to make and configure a repository to host our file (free hosting!). Here’s my repository as an example.\n\n\n  Create a new public GitHub repository, and clone it locally.\n  Put your newly generated assetlinks.json file in /.well-known/, commit &amp; push.\n  In the repository’s settings, set a “Source” for GitHub pages (probably master / main branch).\n  Enter your custom domain’s information.\n\n\nYour settings should look like this, note that “Enforce HTTPS” won’t be available yet, and your site won’t be published yet.\n\n\n\nSetting up DNS in Cloudflare\n\nNow our file is hosted, we need to actually make it available at our URL!\n\nConfiguring the DNS records to properly display the GitHub pages repository was perhaps the trickiest bit of this process. There is an official GitHub walkthrough, but the process simply didn’t work for me, perhaps because I use Cloudflare.\n\nHere’s how I got it working:\n\n\n  In Cloudflare, turn on “Development Mode” under “Quick Actions” on the overview of your domain. This makes sure all changes are visible immediately.\n  On GitHub’s walkthrough, scroll to Step 4 of “Configuring an apex domain”. This contains the IP addresses we need.\n  Using at least 2 of those IPs, add proxied “A” records for your subdomain. It will end up looking like this:\n\n\n\n\nWhen you visit your subdomain’s URL, you should now see some information about your GitHub repository. Whilst it can take up to 24 hours for these changes to propagate, for me it was just a few seconds!\n\nFinal changes on GitHub\n\nNow your subdomain is configured, enable the “Enforce HTTPS” option now available in your GitHub repo’s settings. This needs to be enabled for app linking to work, but can take a few minutes to appear.\n\nI got stuck here for quite a while, as it turns out GitHub treats folders in Pages repositories differently to how I expected. Essentially, you can’t navigate directly to your asset linking file without telling GitHub the folder should be included:\n\n\n  Create the file _config.yml in the root of your project.\n  Put include: [\".well-known\"] inside, and save.\n\n\nVisit your asset links URL (https://yourdomain/.well-known/assetlinks.json), and you should finally see your file!\n\nFinally, check your domain on Google’s asset linking API. You should see your json, followed by **** ERRORS ****\\nNone!\\n, this means it’s all sorted!\n\nIt can take a while for Cloudflare and GitHub changes to propagate, so be prepared to wait a few hours. In the meantime, we can make the necessary changes to the app.\n\nAdding URLs to Android manifest\n\nThe only change we need to make to the manifest is specifying which activity our URL should open. We also want to use autoVerify to automatically verify we own the domain.\n\nThis can be done automatically in Android Studio’s Tools -&gt; App Links Assistant -&gt; URL Mapping Editor:\n\n\n  Click the add button (+)\n  Enter your URL\n  Pick an activity (probably MainActivity)\n  Press OK\n\n\nAn intent filter will then be added to your AndroidManifest.xml looking something like:\n\n&lt;intent-filter android:autoVerify=\"true\"&gt;\n    &lt;action android:name=\"android.intent.action.VIEW\" /&gt;\n    &lt;category android:name=\"android.intent.category.DEFAULT\" /&gt;\n    &lt;category android:name=\"android.intent.category.BROWSABLE\" /&gt;\n    &lt;data android:scheme=\"https\" android:host=\"apod.jakelee.co.uk\" /&gt;\n&lt;/intent-filter&gt;\n\n\nYour screen will end up looking like this, you can click a URL to see it in the manifest:\n\n\n\nConclusion\n\nThat’s it, your app is linked to your domain!\n\nNow, when you try to open links to your domain, your app should automatically open. If this isn’t the case, make sure:\n\n\n  You’re signing your app with the same certificate / key you used to create your assetlinks.json.\n  You don’t see any errors when checking your URL on the API.\n  You’ve tried completely reinstalling your app, to force the verification process.\n  You’re using HTTPS (not HTTP) everywhere.\n  You’ve read through the official tutorial, and there’s no edge cases there that apply to you.\n\n\nThe next steps are actually handling the intent that a universal link will send to your Activity. There’s some starting information in the official App Links tutorial, I’ll also be making a follow up post about supporting universal links and (outdated) custom schema links (e.g. apod://x).\n\nFurther resources\n\n\n  App links guide: https://developer.android.com/training/app-links\n  Verifying app links guide: https://developer.android.com/training/app-links/verify-site-associations\n  Official app links tutorial: https://developer.android.com/studio/write/app-link-indexing\n  My GitHub pages repository: https://github.com/JakeSteam/APODWallpaperSubdomain\n  Technical info on app links: https://chris.orr.me.uk/android-app-linking-how-it-works/\n  GitHub pages custom domain tutorial: https://docs.github.com/en/free-pro-team@latest/github/working-with-github-pages/managing-a-custom-domain-for-your-github-pages-site\n  API to check your app linking file: https://digitalassetlinks.googleapis.com/v1/statements:list?source.web.site=https://apod.jakelee.co.uk&amp;relation=delegate_permission/common.handle_all_urls\n\n"
    } ,
  
    {
      "tags"     : "Actions, BuildConfig, CI, GitHub, Secrets",
      "title"    : "Accessing an Android app secret from GitHub Actions using Gradle",
      "excerpt"  : "Often an open source project will have API keys, auth tokens, and other secrets that definitely shouldn’t end up in source code. In my current open source project (a rewrite of APOD Wallpaper) I needed to store my APOD API key.\n",
      "url"      : "/accessing-android-app-secret-from-github-actions-using-gradle/",
      "date"     : "Oct 9, 2020",
      "content"  : "Often an open source project will have API keys, auth tokens, and other secrets that definitely shouldn’t end up in source code. In my current open source project (a rewrite of APOD Wallpaper) I needed to store my APOD API key.\n\nIn the past, I’ve just added it to my local.properties and removed the file from git, but this approach doesn’t work when using GitHub Actions!\n\nThis post is available as a GitHub gist.\n\nNote: As per a couple of comments, you could skip the properties file and use System.getEnv(x). I personally prefer keeping it in the project’s gradle file, to keep the secret only accessible from the project itself.\n\nApproach to secrets\n\nThe approach to storing the secret isn’t going to change too much, there’ll just be a few changes to cater for GitHub Actions (italic = new):\n\n\n  Store the secret in our local properties\n  Store the secret in GitHub’s “secret” functionality\n  In the CI, load this secret into a new local.properties file.\n  In Gradle, manually load the local.properties file\n  Load the secret into the BuildConfig.\n  At runtime, access this new field.\n\n\n1. Setting up local secret\n\nAll we need to do is open the autogenerated local.properties, and add our secret into it. Make sure to include the speech marks!\n\nAPOD_API_KEY=\"abcd1234\"\n\n\n2. Adding secret to GitHub\n\nNext, we need to go to the repository’s “Settings”, then “Secrets”, then “New secret”. This will let us add a secret with a name &amp; value. Don’t include speech marks this time!\n\n\n\n3. Accessing secret in GitHub Actions\n\nThere’s already plenty of great guides to getting GitHub Actions working with Android (simple, more complex, even more complex). For this project, here’s the full build.yml.\n\nThe only addition we need to make is a new job step in build.yml to put the secret into a new local.properties file. This must be done after the code is checked out, or the file will be put in the wrong location:\n\n- name: Access APOD_API_KEY\n  env:\n    APOD_API_KEY: $\n  run: echo APOD_API_KEY=\\\"$APOD_API_KEY\\\" &gt; ./local.properties\n\n\nThere’s 4 steps to this process:\n\n\n  Access the secret itself ($)\n  Use it to set an environment variable (env: APOD_API_KEY)\n  Write the Groovy code ourselves to set a variable we can access in Gradle (run: echo x = \\\"y\\\")\n  Save this code into a new local.properties file: ( &gt; ./local.properties)\n\n\n4. Loading the local properties file in Gradle\n\nIn our app-level build.gradle, we need to load our properties file manually, then access the key within. This isn’t necessary when running locally, but will be needed for the CI!\n\nWe do this by adding a new function, outside of android {} or dependencies {} etc:\n\nString getApiKey() {\n    def propFile = rootProject.file(\"./local.properties\")\n    def properties = new Properties()\n    properties.load(new FileInputStream(propFile))\n    return properties['APOD_API_KEY']\n}\n\n\n5. Loading the secret into BuildConfig\n\nNext, still in the same file, we need to add our secret into the BuildConfig. I’m using the default config, but it’s pretty straightforward to have different values for different flavours / build types:\n\nandroid {\n    ...\n    defaultConfig {\n        ...\n        buildConfigField (\"String\", \"API_KEY\", getApiKey())\n    }\n}\n\n\n6. Accessing the value at runtime\n\nFinally, the simplest step of all! Once we’ve done a build to populate the BuildConfig, we can just access our secret with BuildConfig.API_KEY. Now, when GitHub actions runs our app can access the secret, and the build passes.\n\n\n\nConclusion\n\nWhilst trying to find a way to store my secret, I was quite surprised there didn’t seem to be any complete guides around. The closest I could find was an unvoted StackOverflow post that had most of the information, and still required figuring a few things out!\n\nCurrently this post’s method only covers the case where there’s 1 secret to store. If multiple are needed, a quick solution would be just manually adding more to each step, but I’m sure it’s not ideal.\n\nGitHub actions is still (somewhat) new, but so far it definitely seems a strong contender to traditional CIs. The “actions” store seems an excellent way to share functionality between projects, and encourage a strong CI community. Having simple tasks like checking out code and setting up the JAVA JDK as actions makes sure everyone is comfortable with the process, whilst keeping the build config readable.\n\nResources\n\n\n  Gist for this post: https://gist.github.com/JakeSteam/4ff98553691d1d30949fb1de6adf83a5\n  Storing entire gradle properties file as a secret: https://stackoverflow.com/questions/61988255/how-to-enable-github-actions-access-gradle-properties\n  Storing single secret in gradle: https://stackoverflow.com/questions/62278936/pass-local-properties-in-build-gradle-android-through-git-hub-secret\n  GitHub secrets: https://docs.github.com/en/free-pro-team@latest/actions/reference/encrypted-secrets\n  GitHub actions: https://github.com/features/actions\n\n"
    } ,
  
    {
      "tags"     : "animations, drawables, objectanimator, xml",
      "title"    : "Programmatically creating and scheduling animations for Android drawable layers with ObjectAnimator",
      "excerpt"  : "Recently I needed to perform a pretty complex animation on an image button. The button needed to move, whilst different parts of it also needed to rotate, fade in and out, and disappear!\n",
      "url"      : "/programmatically-creating-and-scheduling-animations-for-android-drawable-layers-with-objectanimator/",
      "date"     : "Oct 5, 2020",
      "content"  : "Recently I needed to perform a pretty complex animation on an image button. The button needed to move, whilst different parts of it also needed to rotate, fade in and out, and disappear!\n\nTo implement this I combined the animating parts into a single layer list, where they could then be animated without requiring new views. The end result was very smooth, with a very small amount of code written.\n\nIn this post we’ll perform similar effects on a layer list drawable without any XML animations:\n\n&lt;/source&gt;&lt;/wp-content/uploads/2020/10/ezgif.com-gif-maker.webm&gt;\n\nThis post is available as a proof of concept repository, and as a GitHub gist.\n\nPreparing the drawable\n\nThe drawable needs to be a layer-list, with each animation layer having a unique ID. Any sort of item should work, this example will use a shape and a vector drawable.\n\nSince the icon needs to rotate, it needs to be inside a &lt;rotate&gt; tag:\n\n&lt;layer-list xmlns:android=\"http://schemas.android.com/apk/res/android\"&gt;\n    &lt;item android:id=\"@+id/red_circle\"&gt;\n        &lt;shape android:shape=\"oval\" &gt;\n            &lt;solid android:color=\"@android:color/holo_red_dark\" /&gt;\n        &lt;/shape&gt;\n    &lt;/item&gt;\n    &lt;item android:id=\"@+id/icon\"&gt;\n        &lt;rotate android:drawable=\"@drawable/ic_launcher_foreground\" /&gt;\n    &lt;/item&gt;\n&lt;/layer-list&gt;\n\n\nSelecting layers to animate\n\nTo select a layer of the ImageView for animation, we first extract the LayerDrawable, then find the layer we want by ID:\n\nval target = findViewById&lt;ImageView&gt;(R.id.imageview)\nval animationLayers = target.drawable as LayerDrawable    \nval redCircle = animationLayers.findDrawableByLayerId(R.id.red_circle) as GradientDrawable\n\n\nThe type of Drawable required varies depending on how the layer-list is defined. For this example, we only need GradientDrawable for our simple shape, and RotateDrawable for the icon we want to rotate.\n\nThere are 40 subclasses of Drawable, but these 2 will do for now!\n\n\n\nLooking at these .class files will tell you what animations are supported. For example, RotateDrawable has onLevelChange for rotation, but GradientDrawable has setAlpha for changing transparency.\n\nPreparing animations\n\nAll of our animation is going to happen inside a startAnimation(target: ImageView) function, and use ObjectAnimator. Since we’re going to be animating both ImageViews and layer list layers, an important note is needed:\n\n\n  If an ImageView is being used, a float value of the target will be used. For example, the alpha is between 1.0f (fully visible) and 0.0f (fully invisible).\n  If a Drawable is being used (e.g. GradientDrawable / RotateDrawable), an int value of the target will be used. For example, the alpha is instead between 255 (fully visible) and 0 (fully invisible).\n\n\nObjectAnimator provides a simple syntax for creating animations. If we want the red circle layer to fade from fully visible to invisible in 1000ms, we just need:\n\nval redCircleFadeOut = ObjectAnimator.ofInt(redCircle, \"alpha\", 255, 0).setDuration(1000)\n\n\nSimple!\n\nWe need 6 animations in total to move our ImageView left, partially fade out our red circle, rotate our icon left, and then reverse all 3. Note that rotation uses 0-10000, whilst alpha uses 0-255:\n\nval moveImageViewLeft = ObjectAnimator.ofFloat(target, View.TRANSLATION_X, -200f).setDuration(6000)\nval moveImageViewRight = ObjectAnimator.ofFloat(target, View.TRANSLATION_X, 0f).setDuration(6000)\nval redCircleFadeOut = ObjectAnimator.ofInt(redCircle, \"alpha\", 255, 100).setDuration(1000)\nval redCircleFadeIn = ObjectAnimator.ofInt(redCircle, \"alpha\", 100, 255).setDuration(100)\nval iconRotateLeft = ObjectAnimator.ofInt(icon, \"level\", 10000, 1000).setDuration(3000)\nval iconRotateRight = ObjectAnimator.ofInt(icon, \"level\", 1000, 10000).setDuration(300)\n\n\nScheduling animations\n\nUsing AnimatorSet‘s very simple play(x).with(y).after(z) syntax, complex scheduling becomes very readable.\n\nIn our animation, we want to:\n\n\n  Move our ImageView left, fade out our red circle, rotate our icon left.\n  After the icon has finished rotating, rotate it back again and fade the circle back in.\n  After the ImageView has finished moving, move it back.\n\n\nUsing AnimatorSet this can be written as:\n\nAnimatorSet().apply {\n  play(moveImageViewLeft)\n    .with(redCircleFadeOut)\n    .with(iconRotateLeft)\n  play(redCircleFadeIn)\n    .with(iconRotateRight)\n    .after(iconRotateLeft)\n  play(moveImageViewRight)\n    .after(moveImageViewLeft)\n  start()\n}\n\n\nHandling multiple animations\n\nIn the real world, when performing an animation it may be triggered again. When this situation is not handled, all sorts of odd visual effects happen and look awful!\n\nAvoiding overlapping animations\n\nA simple way to avoid overlapping animations is keeping track of the AnimatorSet and cancelling it when a new animation is started:\n\nprivate var animatorSet: AnimatorSet? = null\nprivate fun startAnimation(target: ImageView) {\n  animatorSet?.cancel()\n  animatorSet = AnimatorSet().apply {\n    ...\n    start()\n  }\n}\n\n\nResetting view positions\n\nWhilst most of the layer effects automatically reset when cancelled, the view’s movement is not. As such, we need to create a “reset” function:\n\nval animationReset = { target.translationX = 0f }\n\n\nThis should be triggered when the animation is cancelled (due to a new animation starting), so doOnCancel() should be used. If your animation does not leave views in the same place as they started, doOnEnd() should also be used:\n\nAnimatorSet().apply {\n    ...\n    doOnCancel { animationReset.invoke() }\n    start()\n  }\n}\n\n\nResources\n\n\n  A proof of concept repository is available\n  A GitHub gist is available\n  ObjectAnimator on developer docs\n  AnimationSet on developer docs\n\n"
    } ,
  
    {
      "tags"     : "Android, Community, Dev, Discord, Subreddit",
      "title"    : "Android Discord Communities: 2020 edition",
      "excerpt"  : "Whether working on Android apps, finding new games, or having technical issues, getting real time Android support on places like Discord can be extremely helpful. In this follow-up post to my December 2018 edition, I will cover the main Android Discord communities, and how they have changed in the last 20 months.\n",
      "url"      : "/android-discord-communities-2020-edition/",
      "date"     : "Sep 9, 2020",
      "content"  : "Whether working on Android apps, finding new games, or having technical issues, getting real time Android support on places like Discord can be extremely helpful. In this follow-up post to my December 2018 edition, I will cover the main Android Discord communities, and how they have changed in the last 20 months.\n\nI still help moderate all of these communities, please let me know if there are other communities I’m missing!\n\nAndroid Development Discord Servers\n\nAndroid Dev\n\nIn the last 20 months, the Android Dev server has almost tripled in size from 3k to 8.5k members! This has been helped by the partnership with the /r/AndroidDev subreddit, and helpful new moderators.\n\nThe server has undergone dramatic reorganisation recently, and now has better channel organisation and even multiple “beginner help” channels to avoid overlapping conversations. Finding the right channel is easy with dedicated channels for topics, a #team-up channel for collaborating, and #app-showcase for sharing created apps.\n\n\n\nFlutter Dev\n\nWhilst the Android Dev server’s growth is impressive, the Flutter Dev one is borderline ridiculous! Rising from 1.6k members in 2018 to almost 20k in 2020 and gaining Discord partnership, the server remains an essential resource for Flutter developers.\n\nThis growth has been helped by close partnership with the /r/FlutterDev subreddit, as well as becoming an official community resource. It remains closely paired with the /r/AndroidDev server, and has a dedicated bot that provides Flutter documentation lookups.\n\n\n\nGeneral Android Discord Servers\n\nAndroid\n\nThe Android server has #whatphone, #tech-support, and #android-questions channels for support, but the main highlight remains the… unusual community in #general (formerly #offtopic). The server has a new #starboard for the best messages and extra channels for chat regulars.\n\nWhilst the development servers have been pairing more closely with their subreddits, the Android discord has instead split completely due to vastly different communities. Since the split, it has enjoyed excellent growth (12k -&gt; 18k) from Discord’s discovery system, and remains a Discord partner. The server also now takes feedback much more directly from the community, via the new #suggestions channel.\n\nDisclaimer: I now own the server instead of just moderating it!\n\n\n\nAndroid Gaming\n\nWhilst quieter than the above servers, the Android Gaming server has continued to steadily grow, helped by the subreddit partnership. There remains an excellent list of #game-discords, as well as channels for game #recommendations and of course #android-gaming.\n\nIt has doubled in size to just over 3k members, and has a cute new icon!\n\n\n\nAndroid Questions\n\nThis server is unfortunately a bit neglected, and questions receive quicker answers on the Android or Android Dev servers instead. However it continues to grow, over doubling in size to reach 1.1k members.\n\n\n"
    } ,
  
    {
      "tags"     : "Assets, Games, Indie, Resources",
      "title"    : "Should I use a free / cheap resource pack in my game?",
      "excerpt"  : "For small / single-person dev teams, art assets can be one of the trickiest parts of the game making process. Even the most interesting game mechanics won’t be appreciated by many unless the game is visually appealing. I consider myself a reasonable programmer, but my attempts at creating resources are… best not shown to others!\n",
      "url"      : "/should-i-use-a-free-cheap-resource-pack-in-my-game/",
      "date"     : "Aug 21, 2020",
      "content"  : "For small / single-person dev teams, art assets can be one of the trickiest parts of the game making process. Even the most interesting game mechanics won’t be appreciated by many unless the game is visually appealing. I consider myself a reasonable programmer, but my attempts at creating resources are… best not shown to others!\n\nIn my games I tend to purchase then modify resource packs from others. In this post I’ll cover how to find a resource pack, as well as the advantages / disadvantages that come with them.\n\nWhat to look for in resource packs\n\nPurchasing a resource pack / packs that ends up not being used can be a very time consuming &amp; expensive waste. To avoid this, I recommend keeping the following 5 things in mind when picking:\n\n\n  Does it have odd dimensions / art style?\n\n\n\nWhilst having a unique art style can be a positive, having assets that won’t match packs purchased from elsewhere ties you into one artist. For example, whilst 16×16 / 32×32 are common pixel art sizes, a 19×19 pack would make finding compatible artwork tricky.\n\n  Does it cover all situations? A resource pack is no good if it only covers half your use cases. Your game will likely add future content, you’ll want to have plenty of assets spare for that. Buying 1000 assets and only using 100 to start with is okay!\n  What’s the license / price? Get ready to revise on tl;dr Legal! It’s absolutely essential any pack you use has a license compatible with your game. For example, CC0 content can be modified, included in commercial work, and has no requirements, making it the ideal choice.\n  Is it appropriate? Just as bright colourful art wouldn’t work in a gritty war shooter, don’t put dull greys and browns into a kid’s game!\n  Do you like it? Sounds silly, but it’s easy to forget you need to like the artwork too! You’re going to be looking at it for many hours, make sure you like it overall. No point getting a good deal on a pack if you end up switching away in a few weeks.\n\n\nWhere to find resource packs\n\nNow you know what you’re looking for a pack, it’s time to find one!\n\nIn the past, I’ve used:\n\n\n  Kenney.nl: The absolute best place for free assets There are also a few paid packs cheaply available, each of which contains literally thousands of resources. Kenney’s assets usually feature all the variations needed, in multiple formats, and even supplementary material (e.g. 3D models) to help you create similar assets. I just checked my 3 purchased packs, and they contain nearly 50,000 assets for just $30!\n  itch.io: My personal favourite for paid work. The quality of content on itch.io varies quite a lot, and asset packs often seem to not actually include many assets! That being said, the wide variety of art styles can be very helpful, and you can also filter by tags. The tools section might also be helpful.\n  OpenGameArt.org: Excellent for those on a budget, all art on here is free. You can filter by license type, but the 100% free nature of the site unfortunately can result in a lot of low quality artwork.\n  DeviantArt: This is definitely a last resort. There’s a lot of NSFW / irrelevant content, but I have found some high quality assets for free here in the past.\n\n\nAn example pack: 7soul’s assets\n\n\n7soul’s packs on itch.io are my personal favourites, and provide almost all of the assets for Pixel Blacksmith. I used the UI pack, icon pack, and sprite pack, all of which work smoothly together. You may also recognize his work from Forager!\n\nThey’re very reasonably priced, have a consistent, unique style, and have lots of related packs allowing for future expansion. As the item icons pack contains 1700+ icons(!), I was confident it would cover all my item needs, even though I ended up performing a few recolours for different item tiers. \n\n\nIn the 4 years since I made Pixel Blacksmith, I occasionally spot other games using the same assets! A couple that I’ve personally found and enjoyed are:\n\n\n  Idle Slayer\n  Minesweeper: Collector\n  Wintersun MMORPG\n\n\nAdvantages\n\nThe biggest advantage of using a resource pack is getting high quality art cheaply. Commissioning some of these packs would cost hundreds / thousands of dollars, so getting them instantly for $10-30 is amazing! \n\n\nYou also have the advantage of knowing what the resources will look like before paying, and are often able to get a refund if they end up being not what was expected. I’ve also found that having assets gives me a good “feel” for the game, and can help my creativity. For example, Kenney’s library preview (see image on right) was the main inspiration for Pixel Bookshop!\n\nFinally, using resource packs means you’ll occasionally see characters you know from your games appearing elsewhere! Whilst playing Idle Slayer, it was nice seeing a visitor wasp in Pixel Blacksmith appearing as an enemy, almost like seeing an old friend again.\n\nDisadvantages\n\nOf course, whilst seeing the assets you’re using elsewhere can be a nice experience, it isn’t always. In the past I’ve been accused of theft / stealing assets when they come from a pack (see below image!). Users may see assets from their favourite game reused, and assume another developer has stolen it, without considering alternatives. Whilst users often correct their negative review once the situation is explained, they don’t always!\n\n\n\nPerhaps a more important disadvantage is the lack of control / ownership. You can’t change the license of the assets and may struggle to sell merchandise. Similarly, if you want a specific new asset in the pack’s art style you’ll either need to commission the artist or try to make it yourself, both of which can be tricky.\n\nI also found that the direction of the game itself often gets influenced by the assets! If a pack you’re using has 5 different types of weapon but you originally wanted 7, it’s easier to adjust your plans than make new assets.\n\nConclusion\n\nOverall, I’m really, really glad resource packs / asset packs exist. They let independent artists make some money from their work, whilst letting game devs use high quality assets without breaking the bank. Plus, once you’ve purchased a pack once you can reuse it in future games.\n\nIf you’re a one person dev team, it seems the best solution by far!\n"
    } ,
  
    {
      "tags"     : "Git, GitHub",
      "title"    : "Exploring pull requests with GitHub's rich diff functionality",
      "excerpt"  : "Like many developers, I spend a surprisingly large amount of time reviewing other people’s code. In fact, according to GitHub that’s around 20% of my day!\n",
      "url"      : "/exploring-pull-requests-with-githubs-rich-diff-functionality/",
      "date"     : "Aug 12, 2020",
      "content"  : "Like many developers, I spend a surprisingly large amount of time reviewing other people’s code. In fact, according to GitHub that’s around 20% of my day!\n\n\n\nWhen reviewing pull requests, code changes are very easy to review and approve. However, comparing images can be much harder to check, since by default GitHub only shows an unintuitive “Binary file not shown” message. Luckily, I recently discovered the rarely mentioned “rich diff” feature that makes this so, so much easier. I’ll briefly run through the functionality it offers, all screenshots in this post are from my Rich Diff repo.\n\nOverall\n\nFirst of all, how do you access rich diff? Simple, click the “page” icon next to many file types! Once clicked, this will compare the two files in a much more helpful way. If no “page” icon is visible, rich diff is not available.\n\n\n\nImage rich diff\n\nImages are probably the best use cases for rich diff. I created a collection of test images (SVG, PNG, JPG, GIF, BMP), committed them, and then committed new versions of each.\n\nI found SVGs, PNGs, JPGs, and GIFs can use rich diff, but BMPs cannot. For the compatible file types, there are 3 options for the rich diff:\n\n2-up\n\n\n\nThis mode displays the images side by side, as well as their width, height, and file size. This is a great way to notice an image has slightly changed dimensions, since this might not be noticeable with the naked eye.\n\nUnfortunately, this mode does not help when identifying small visual changes within the image itself, the other modes are better for that.\n\nSwipe\n\n\n\nThis mode displays the two versions of the image with a left to right slider over the top.\n\nThis is an excellent way of noticing small changes within an image, whilst still keeping track of the overall image.\n\nOnion Skin\n\n\n\nThis mode overlays the new image over the old one, and lets you control the transparency.\n\nJust like “Swipe”, this lets you easily see small changes, whilst also being able to see the entirety of both images at all times.\n\nDocument rich diff\n\nWhilst images performed well, I was curious if common document types would work. In a word… no.\n\nAs before, I created &amp; updated a selection of common formats (DOC, DOCX, HTML, PDF, RTF, MD), and only MD (markdown) had rich diff. The RTF and HTML files did show the code changes, but this isn’t particularly helpful for a verbose format like RTF!\n\n\n\nThe Markdown file fared much better, showing a very helpful visual indicator of what has been added and removed.\n\nThe coloured bars on the left indicate the line status (first line changed, second line added). The coloured highlights in the changed line indicate the removed and added sections, in an easy to understand format.\n\n\n\nWhilst this indicator usually works well, in some commits it instead shows an entire section as changed instead of only the specific lines.\n\nSummary\n\nIn summary, rich diff is an extremely powerful feature that is nowhere near as well known as it should be. However, the inability to enable it by default, or to set a default image comparison type both make it a bit awkward to use.\n\nOne likely reason for the feature not being heavily promoted is the extra processing time on GitHub’s side required for a rich diff. At least in 2016, larger Markdown files could take up to 5 seconds, which is GitHub’s rich diff timeout.\n\nHopefully this post helps you next time you need to compare changed images in a GitHub pull request. It was a lifesaver when I recently needed to look at a colleague‘s PR containing 180 JPGs!\n\n\n"
    } ,
  
    {
      "tags"     : "Design, Drawable, Gradient, XML",
      "title"    : "A few experiments with Android drawable gradients",
      "excerpt"  : "After recently struggling to make a small modification to a simple translucent overlay, I decided to experiment with gradients in Android drawables. After a few hours, I discovered a few new possibilities! Drawable gradients seem to be rarely used despite their simple syntax, with people preferring to use SVGs or static images.\n",
      "url"      : "/a-few-experiments-with-android-drawable-gradients/",
      "date"     : "Jul 31, 2020",
      "content"  : "After recently struggling to make a small modification to a simple translucent overlay, I decided to experiment with gradients in Android drawables. After a few hours, I discovered a few new possibilities! Drawable gradients seem to be rarely used despite their simple syntax, with people preferring to use SVGs or static images.\n\nI’ve included a few example outputs in this post, hopefully these help those struggling to create a gradient. I also recommend taking a look at AngryTools’ gradient generator (Android tab), to easily generate the XML for simpler gradients automatically.\n\nThis post is also available as a GitHub repo.\n\n\n    NotesGradientXML\n    \n        Simple linear gradientA really simple gradient to start, our first type is \"linear\". All we have is a startColor of white and an endColor of black, resulting in the nice smooth transition shown.\n        \n        &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;\n&lt;shape xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;\n   &lt;gradient android:startColor=&quot;@android:color/white&quot; android:endColor=&quot;@android:color/black&quot; /&gt;\n&lt;/shape&gt;\n    \n    \n        Centre offsetting Whilst this gradient might look very similar to the previous, there's a secret inside: centerY.  Setting a centre colour (holo_blue_dark in this case) allows for slightly more complex gradients, but the interesting bit happens when you redefine where the centre is. centerX and centerY will both be used extensively throughout this post, and work by redefining where the centre colour should appear. For example, a value of 20% or 0.2 will ensure your centerColor appears 20% down the drawable vertically.\n        \n        &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; \n&lt;shape xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;\n   &lt;gradient android:startColor=&quot;@android:color/white&quot; android:centerColor=&quot;@android:color/holo_blue_dark&quot; android:endColor=&quot;@android:color/black&quot; android:centerY=&quot;0.2&quot; /&gt;\n&lt;/shape&gt;\n    \n    \n        Overlapping layersBuilding up on our previous gradient, adding an extra layer (via layer-list) drastically increases the complexity of the output. layer-list simply lets you overlap multiple gradients without making new ImageViews or drawables.  In this case, a transparent -&gt; black gradient has been added on top of our existing white -&gt; blue -&gt; black gradient, at an angle (essentially rotation) of 180.\n        \n        &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; \n&lt;layer-list xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;\n   &lt;item&gt;\n      &lt;shape&gt;\n         &lt;gradient android:startColor=&quot;@android:color/white&quot; android:centerColor=&quot;@android:color/holo_blue_dark&quot; android:endColor=&quot;@android:color/black&quot; android:centerY=&quot;0.2&quot; /&gt;\n      &lt;/shape&gt;\n   &lt;/item&gt;\n   &lt;item&gt;\n      &lt;shape&gt;\n         &lt;gradient android:startColor=&quot;@android:color/black&quot; android:endColor=&quot;@android:color/transparent&quot; android:angle=&quot;180&quot;/&gt;\n      &lt;/shape&gt;\n   &lt;/item&gt;\n&lt;/layer-list&gt;\n    \n    \n        Overlapping layers at the same angle Just as the last gradient overlapped gradients at right angles, you can also overlap them without rotating. If a layer has a transparent startColor and endColor, but a non-transparent centerColor, it will appear as a horizontal strip of colour. Offsetting this strip using centerY, then repeating the process, allows a full rainbow of colours to be created. Note that this gradient also has a base white layer, to help the gradient be visible.\n        \n        &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; \n&lt;layer-list xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;\n   &lt;item&gt;\n      &lt;shape&gt;\n         &lt;solid android:color=&quot;@android:color/white&quot; /&gt;\n      &lt;/shape&gt;\n   &lt;/item&gt;\n   &lt;item&gt;\n      &lt;shape&gt;\n         &lt;gradient android:startColor=&quot;@android:color/holo_purple&quot; android:centerColor=&quot;@android:color/transparent&quot; android:endColor=&quot;@android:color/transparent&quot; android:centerY=&quot;0.4&quot; /&gt;\n      &lt;/shape&gt;\n   &lt;/item&gt;\n   &lt;item&gt;\n      &lt;shape&gt;\n         &lt;gradient android:startColor=&quot;@android:color/transparent&quot; android:centerColor=&quot;@android:color/holo_orange_light&quot; android:endColor=&quot;@android:color/transparent&quot; android:centerY=&quot;0.4&quot; /&gt;\n      &lt;/shape&gt;\n   &lt;/item&gt;\n   &lt;item&gt;\n      &lt;shape&gt;\n         &lt;gradient android:startColor=&quot;@android:color/transparent&quot; android:centerColor=&quot;@android:color/holo_blue_light&quot; android:endColor=&quot;@android:color/transparent&quot; android:centerY=&quot;0.7&quot; /&gt;\n      &lt;/shape&gt;\n   &lt;/item&gt;\n   &lt;item&gt;\n      &lt;shape&gt;\n         &lt;gradient android:startColor=&quot;@android:color/transparent&quot; android:centerColor=&quot;@android:color/transparent&quot; android:endColor=&quot;@android:color/holo_green_dark&quot; /&gt;\n      &lt;/shape&gt;\n   &lt;/item&gt;\n&lt;/layer-list&gt;\n    \n    \n        Radial gradients So far we've only seen linear gradients, now we'll use radial gradients. The easiest way of thinking about them is as a \"point\" of colour, radiating out. centerX and centerY can be used to move this point anywhere on the canvas, in this case 10% from the left and 10% from the top.  Again, the startColor, centerColor, and endColor are used to set the colour, along with gradientRadius being used to set the overall size of the gradient.\n        \n        &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; \n&lt;shape xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; android:shape=&quot;rectangle&quot;&gt;\n   &lt;gradient android:type=&quot;radial&quot; android:gradientRadius=&quot;100%&quot; android:startColor=&quot;@android:color/black&quot; android:centerColor=&quot;@android:color/holo_blue_light&quot; android:centerX=&quot;0.1&quot; android:centerY=&quot;0.1&quot; android:endColor=&quot;@android:color/white&quot; /&gt;\n&lt;/shape&gt;\n    \n    \n        Floating blobs Combining multiple radial gradients using the same overlapping technique as our \"vertical rainbow\" before, we can end up with this collection of floating blobs. This effect is often hunted for by people looking to create an Instagram style logo, and is very easy to achieve. So long as you know your colours, it's just a matter of adjusting the radius, x position, and y position until each blob is in the correct place. I used this to answer a question on StackOverflow, and the OP raised a reasonable counterpoint. If you need a particularly complex gradient, you could just try exporting an SVG / PNG. However, with vector graphics sometimes gradients aren't translated properly, and a PNG will either be too large, or may not scale perfectly to the user's screen. If possible, creating an image as a gradient drawable will ensure it is perfect!\n        \n        &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; \n&lt;layer-list xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;\n   &lt;item&gt;\n      &lt;shape android:layout_height=&quot;wrap_content&quot;&gt;\n         &lt;solid android:color=&quot;@android:color/black&quot; /&gt;\n      &lt;/shape&gt;\n   &lt;/item&gt;\n   &lt;item&gt;\n      &lt;shape&gt;\n         &lt;gradient android:type=&quot;radial&quot; android:gradientRadius=&quot;100%&quot; android:startColor=&quot;@android:color/holo_purple&quot; android:centerX=&quot;0.1&quot; android:centerY=&quot;0.1&quot; android:endColor=&quot;@android:color/transparent&quot; /&gt;\n      &lt;/shape&gt;\n   &lt;/item&gt;\n   &lt;item&gt;\n      &lt;shape&gt;\n         &lt;gradient android:type=&quot;radial&quot; android:gradientRadius=&quot;70%&quot; android:startColor=&quot;@android:color/holo_orange_light&quot; android:centerX=&quot;0.8&quot; android:centerY=&quot;0.5&quot; android:endColor=&quot;@android:color/transparent&quot; /&gt;\n      &lt;/shape&gt;\n   &lt;/item&gt;\n   &lt;item&gt;\n      &lt;shape&gt;\n         &lt;gradient android:type=&quot;radial&quot; android:gradientRadius=&quot;40%&quot; android:startColor=&quot;@android:color/holo_blue_light&quot; android:centerX=&quot;0.8&quot; android:centerY=&quot;0.1&quot; android:endColor=&quot;@android:color/transparent&quot; /&gt;\n      &lt;/shape&gt;\n   &lt;/item&gt;\n   &lt;item&gt;\n      &lt;shape&gt;\n         &lt;gradient android:type=&quot;radial&quot; android:gradientRadius=&quot;70%&quot; android:startColor=&quot;@android:color/holo_green_light&quot; android:centerX=&quot;0.2&quot; android:centerY=&quot;0.8&quot; android:endColor=&quot;@android:color/transparent&quot; /&gt;\n      &lt;/shape&gt;\n   &lt;/item&gt;\n   &lt;item&gt;\n      &lt;shape&gt;\n         &lt;gradient android:type=&quot;radial&quot; android:gradientRadius=&quot;50%&quot; android:startColor=&quot;@android:color/holo_red_light&quot; android:centerX=&quot;0.7&quot; android:centerY=&quot;0.85&quot; android:endColor=&quot;@android:color/transparent&quot; /&gt;\n      &lt;/shape&gt;\n   &lt;/item&gt;\n&lt;/layer-list&gt;\n    \n    \n        Sweep gradient The final type of gradients are sweep. These don't seem to make sense at first glance, I find the easiest way of thinking of them is as a \"cone\" shaped linear gradient, viewed from above. However you interpret them, they still use all the attributes we've picked up in previous gradients.\n        \n        &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; \n&lt;shape xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;  android:shape=&quot;rectangle&quot;&gt;  &lt;gradientandroid:startColor=&quot;@android:color/holo_blue_dark&quot;android:endColor=&quot;@android:color/holo_orange_dark&quot;android:type=&quot;sweep&quot; /&gt; &lt;/shape&gt;\n    \n    \n        Sweep offsets Whilst not quite as pretty as the \"rainbow\" or \"floating blobs\" seen with other gradients, offsetting radial drawables creates a pretty odd effect.  I'm not entirely sure I can think of a valid use case for this, but presumably someone needs a gradient that looks like an open doorway!\n        \n        &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; \n&lt;layer-list xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;\n   &lt;item&gt;\n      &lt;shape&gt;\n         &lt;solid android:color=&quot;@android:color/black&quot; /&gt;\n      &lt;/shape&gt;\n   &lt;/item&gt;\n   &lt;item&gt;\n      &lt;shape&gt;\n         &lt;gradient android:type=&quot;sweep&quot; android:centerX=&quot;0.3&quot; android:centerY=&quot;0.1&quot; android:startColor=&quot;@android:color/holo_red_dark&quot; android:centerColor=&quot;@android:color/transparent&quot; android:endColor=&quot;@android:color/transparent&quot;/&gt;\n      &lt;/shape&gt;\n   &lt;/item&gt;\n   &lt;item&gt;\n      &lt;shape&gt;\n         &lt;gradient android:type=&quot;sweep&quot; android:centerX=&quot;0.8&quot; android:centerY=&quot;0.3&quot; android:startColor=&quot;@android:color/holo_blue_dark&quot; android:centerColor=&quot;@android:color/transparent&quot; android:endColor=&quot;@android:color/transparent&quot;/&gt;\n      &lt;/shape&gt;\n   &lt;/item&gt;\n   &lt;item&gt;\n      &lt;shape&gt;\n         &lt;gradient android:type=&quot;sweep&quot; android:centerX=&quot;0.1&quot; android:centerY=&quot;0.5&quot; android:startColor=&quot;@android:color/holo_green_dark&quot; android:centerColor=&quot;@android:color/transparent&quot; android:endColor=&quot;@android:color/transparent&quot;/&gt;\n      &lt;/shape&gt;\n   &lt;/item&gt;\n   &lt;item&gt;\n      &lt;shape&gt;\n         &lt;gradient android:type=&quot;sweep&quot; android:centerX=&quot;0.6&quot; android:centerY=&quot;0.7&quot; android:startColor=&quot;@android:color/holo_orange_dark&quot; android:centerColor=&quot;@android:color/transparent&quot; android:endColor=&quot;@android:color/transparent&quot;/&gt;\n      &lt;/shape&gt;\n   &lt;/item&gt;\n   &lt;item&gt;\n      &lt;shape&gt;\n         &lt;gradient android:type=&quot;sweep&quot; android:centerX=&quot;0.1&quot; android:centerY=&quot;0.9&quot; android:startColor=&quot;@android:color/holo_purple&quot; android:centerColor=&quot;@android:color/transparent&quot; android:endColor=&quot;@android:color/transparent&quot;/&gt;\n      &lt;/shape&gt;\n   &lt;/item&gt;\n&lt;/layer-list&gt;\n    \n    \n        Sweep rotations Just like the last gradient, I can't think of a valid use case for this! Wrapping each shape inside a rotate allows rotating it at any angle, although interestingly it still retains the \"edges\" from the original shape. I suspect this is solvable by rotating the gradient not the shape, which might produce a more aesthetically pleasing output.\n        \n        &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; \n&lt;layer-list xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;\n   &lt;item&gt;\n      &lt;shape&gt;\n         &lt;solid android:color=&quot;@android:color/black&quot; /&gt;\n      &lt;/shape&gt;\n   &lt;/item&gt;\n   &lt;item&gt;\n      &lt;rotate android:fromDegrees=&quot;66&quot; android:toDegrees=&quot;0&quot; android:pivotY=&quot;50%&quot; android:pivotX=&quot;50%&quot;&gt;\n         &lt;shape&gt;\n            &lt;gradient android:type=&quot;sweep&quot; android:centerX=&quot;0.3&quot; android:centerY=&quot;0.5&quot; android:startColor=&quot;@android:color/holo_red_dark&quot; android:centerColor=&quot;@android:color/transparent&quot; android:endColor=&quot;@android:color/transparent&quot;/&gt;\n         &lt;/shape&gt;\n      &lt;/rotate&gt;\n   &lt;/item&gt;\n   &lt;item&gt;\n      &lt;rotate android:fromDegrees=&quot;290&quot; android:toDegrees=&quot;0&quot; android:pivotY=&quot;40%&quot; android:pivotX=&quot;30%&quot;&gt;\n         &lt;shape&gt;\n            &lt;gradient android:type=&quot;sweep&quot; android:centerX=&quot;0.8&quot; android:centerY=&quot;0.3&quot; android:startColor=&quot;@android:color/holo_blue_dark&quot; android:centerColor=&quot;@android:color/transparent&quot; android:endColor=&quot;@android:color/transparent&quot;/&gt;\n         &lt;/shape&gt;\n      &lt;/rotate&gt;\n   &lt;/item&gt;\n   &lt;item&gt;\n      &lt;rotate android:fromDegrees=&quot;18&quot; android:toDegrees=&quot;0&quot; android:pivotY=&quot;40%&quot; android:pivotX=&quot;30%&quot;&gt;\n         &lt;shape&gt;\n            &lt;gradient android:type=&quot;sweep&quot; android:centerX=&quot;0.1&quot; android:centerY=&quot;0.5&quot; android:startColor=&quot;@android:color/holo_green_dark&quot; android:centerColor=&quot;@android:color/transparent&quot; android:endColor=&quot;@android:color/transparent&quot;/&gt;\n         &lt;/shape&gt;\n      &lt;/rotate&gt;\n   &lt;/item&gt;\n   &lt;item&gt;\n      &lt;rotate android:fromDegrees=&quot;280&quot; android:toDegrees=&quot;0&quot; android:pivotY=&quot;50%&quot; android:pivotX=&quot;30%&quot;&gt;\n         &lt;shape&gt;\n            &lt;gradient android:type=&quot;sweep&quot; android:centerX=&quot;0.6&quot; android:centerY=&quot;0.7&quot; android:startColor=&quot;@android:color/holo_orange_dark&quot; android:centerColor=&quot;@android:color/transparent&quot; android:endColor=&quot;@android:color/transparent&quot;/&gt;\n         &lt;/shape&gt;\n      &lt;/rotate&gt;\n   &lt;/item&gt;\n   &lt;item&gt;\n      &lt;rotate android:fromDegrees=&quot;0&quot; android:toDegrees=&quot;0&quot; android:pivotY=&quot;50%&quot; android:pivotX=&quot;30%&quot;&gt;\n         &lt;shape&gt;\n            &lt;gradient android:type=&quot;sweep&quot; android:centerX=&quot;0.0&quot; android:centerY=&quot;0.0&quot; android:startColor=&quot;@android:color/holo_purple&quot; android:centerColor=&quot;@android:color/transparent&quot; android:endColor=&quot;@android:color/transparent&quot;/&gt;\n         &lt;/shape&gt;\n      &lt;/rotate&gt;\n   &lt;/item&gt;\n&lt;/layer-list&gt;\n    \n    \n        Sweep split Finally, one little curiosity about sweep gradients. By offsetting the centerX very far to the left, you'll end up with a top and bottom that are solid colours. This creates an interesting effect, although it could obviously be done much easier by using solid! If you need a similar gradient, I recommend reading the answers on this StackOverflow question for simpler ways of achieving it.\n        \n        &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; \n&lt;shape xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;  android:shape=&quot;rectangle&quot;&gt;\n   &lt;gradient android:startColor=&quot;@android:color/red&quot; android:endColor=&quot;@android:color/holo_orange_dark&quot; android:centerX=&quot;-99&quot; android:type=&quot;sweep&quot; /&gt;\n   &lt;corners android:radius=&quot;20dp&quot; /&gt;\n&lt;/shape&gt;\n     \n\n"
    } ,
  
    {
      "tags"     : "density, dpi, UX, zeplin",
      "title"    : "Avoiding a 1 pixel line on Zeplin exports, or why density matters",
      "excerpt"  : "Recently I needed to update some marketing images in an Android app, based on our designer’s Zeplin screens.\n",
      "url"      : "/avoiding-a-1-pixel-line-on-zeplin-exports-or-why-density-matters/",
      "date"     : "May 5, 2020",
      "content"  : "Recently I needed to update some marketing images in an Android app, based on our designer’s Zeplin screens.\n\nExporting &amp; using these images is usually no problem, but this time our QA reported the images had an unusual white line at the bottom or right on some devices! I manually fixed them in PhotoShop, then hunted for the root cause…\n\n\n\nDensities\n\nTo understand why this happens, we first need to quickly understand Android’s densities. Different devices have differences in quality &amp; size of screen, so to make a 2cm wide image on one device might need 50 pixels, on another it might need 250. \n\nThis is why we package difference densities of every image, so we can display smaller images on smaller / lower resolution devices, and vice versa. On Android we primarily deal with the following 5 densities, which can all be expressed as multiples of each other: mdpi(1x), hdpi (1.5x), xhdpi (2x), xxhdpi (3x), and xxxhdpi (4x).\n\nThe problem\n\nThe specific asset we were using had a resolution of 3072×444 pixels at the highest density, that is then downscaled for our various densities:\n\n\n  xxxhdpi: 3072×444\n  xxhdpi: 2304×333\n  xhdpi: 1536×222\n  hdpi: 1152×166.5\n  mdpi: 768×111\n\n\nNotice the non-whole number there? That’s a problem!\n\nWhen Zeplin is generating this asset for export, it rounds the size up to 1152×167. However, it has no data for what to put in there so leaves it as a transparent pixel. This is usually fine, unless you’re exporting as as a JPG without transparency, in which case you’ll end up with… our white pixel row / column.\n\nThe solution\n\nLuckily, this is really, really easy to fix. If our xxxhdpi asset was instead 3072×440, we’d now have the much nicer:\n\n\n  xxxhdpi: 3072×440\n  xxhdpi: 2304×330\n  xhdpi: 1536×220\n  hdpi: 1152×165\n  mdpi: 768×110\n\n\nNow when we export our assets, we end up with the following (old on top, new on bottom), notice the lack of white pixel?\n\n\n\nThere we go! So long as the mdpi asset has an even number of pixels in it’s width and height, there’ll be no problems.\n"
    } ,
  
    {
      "tags"     : "CI, Git, Slack, Travis",
      "title"    : "Posting a Slack message from Travis CI",
      "excerpt"  : "As part of my ongoing mission to rewrite our CI system, the final step is letting QA know that a new build is available. They can’t test it if they don’t know it’s there!\n",
      "url"      : "/posting-a-slack-message-from-travis-ci/",
      "date"     : "Apr 27, 2020",
      "content"  : "As part of my ongoing mission to rewrite our CI system, the final step is letting QA know that a new build is available. They can’t test it if they don’t know it’s there!\n\nWe’ll be using our CI’s bash script for this, the start of this article describes how to create one if you haven’t already.\n\nNot interested in the full tutorial? Here’s the final Gist, and here’s what we’ll end up with:\n\n\n\nFormatting a Slack message\n\nThe first step is telling Slack how our message should look. Slack has a really nice online visualiser for messages using their “Block Kit” syntax. Using one of their templates, it’s very easy to quickly build a message with example data and preview it on desktop or mobile.\n\nHere is the template I created, it might be helpful as a starting point for your own.\n\n\n\nIn my messages, I display metadata QA / other devs might find useful: branch name, build number, commit message, commit hash, debuggable state.\n\nI’ve also included 4 buttons. One for the Google Play Internal App Sharing link (guide to setting it up), one for help installing, one for the Travis build, and one for the commit’s link on GitHub.\n\nGetting a Slack webhook\n\nSlack has an official guide to creating a webhook URL, but it is much more complicated than necessary. The essential steps are:\n\n\n  Create a new app.\n  Add the “Incoming WebHooks” app to your Slack workspace by clicking “Add to Slack” from the app management page (this will be “Request Configuration” if you’re not an admin).\n  Select which room the messages should go to (picture). It might be helpful setting this to a private message with yourself whilst testing!\n  Once added, scroll down to “Integration settings” (picture), and customise the name and avatar (emoji or uploaded image).\n  Copy the “Webhook URL”.\n  Save settings.\n\n\nPosting messages to Slack\n\nFrom your existing bash script (guide to setting it up if you need to), we just need to do a simple POST to our webhook. This assumes you’ve defined your Slack message’s JSON ($DATA) &amp; webhook URL ($WEBHOOK_URL) already:\n\nHTTP_RESPONSE=$(curl --silent --write-out \"HTTPSTATUS:%{http_code}\" \\\n    --header \"Content-type: application/json\" \\\n    --request POST \\\n    --data \"$DATA\" \\\n    \"$WEBHOOK_URL\")\nHTTP_BODY=$(echo ${HTTP_RESPONSE} | sed -e 's/HTTPSTATUS\\:.*//g')\nHTTP_STATUS=$(echo ${HTTP_RESPONSE} | tr -d '\\n' | sed -e 's/.*HTTPSTATUS://')\nif [[ ${HTTP_STATUS} != 200 ]]; then\n  echo -e \"Sending Slack notification failed.\\nStatus: $HTTP_STATUS\\nBody: $HTTP_BODY\\nExiting.\"\n  exit 1\nfi\n\n\nThis short script will send the custom message to Slack, and display any errors if they occur.\n\nPutting it all together\n\nYou should now have everything you need to create a function that you can invoke in your scripts.\n\nWe’ll put a few placeholders (e.g. $BRANCH) in our message, and replace them when the script runs. I’m defining all of my environment variables at the start, so the script can be easily migrated to another CI if necessary, but some variables still need to be passed to the function.\n\nHere’s the full Gist, make sure you define / pass all your variables!\n\nFurther improvements\n\nIt might be useful to tag user(s) in your message. This can be done by adding their user ID somewhere in your message in this format: &lt;@theiruserid&gt;, which can be found by:\n\n\n  Clicking the user whose ID you want to find.\n  Clicking “View full profile”\n  Pressing the 3 dot icon, you can then copy their member ID:\n\n\n\n\nAnother improvement would be stopping the “warning” icon that appears next to a clicked button. This appears because Slack is trying to transfer (empty) data to the arbitrary URL we’re using, which isn’t accepting it.\n\nUnfortunately there doesn’t seem to be an easy fix, since we’re using simple webhooks and not anything more advanced.\n\n\n"
    } ,
  
    {
      "tags"     : "Ferdi, GitHub, JavaScript, Tutorial",
      "title"    : "Super simple guide to adding a new Ferdi service recipe",
      "excerpt"  : "In my last post I gave a brief overview of the messaging browser Ferdi, and why I love it so much. I noticed there wasn’t a recipe for Nextdoor messages yet, so I decided to create it!\n",
      "url"      : "/super-simple-guide-to-adding-a-new-ferdi-service-recipe/",
      "date"     : "Apr 13, 2020",
      "content"  : "In my last post I gave a brief overview of the messaging browser Ferdi, and why I love it so much. I noticed there wasn’t a recipe for Nextdoor messages yet, so I decided to create it!\n\nI found the documented process a little confusing, hopefully this guide helps others avoid the same issues I ran into. The finished recipe can be downloaded here, and should be in the next update of Ferdi. I’m using Windows, but instructions are provided for Mac &amp; Linux.\n\nMaking your Ferdi recipe\n\nGetting started\n\nWhilst it is possible to create a recipe from scratch, it’s far easier to use an existing one as a starting point. Just navigate to Ferdi’s recipes in one of the following locations:\n\n\n  Mac: ~/Library/Application Support/Ferdi/recipes/\n  Windows: %appdata%/Ferdi/recipes/\n  Linux: ~/.config/Ferdi/recipes/\n\n\nOnce you’re there, create a folder called “dev”, and copy one of the existing recipe folders into it. I used Discord, as it seemed to have simpler config files than my other recipes. Here’s how your recipes folder should look, with a copied folder inside dev:\n\n\n\nCreating your recipe\n\nThis is going to be the bulk of the work! Whilst the 6 required files can be confusing initially, they’re actually very straight forward. I’d strongly recommend looking at my finished recipe if any steps seem unclear!\n\nRename your copied folder to the name of your service (in my case “nextdoor”) before making any changes. Then, update each file to work with your new service.\n\nREADME.md: This is just a simple text file to describe your recipe. Just update the service name in here in any text editor.\n\nicon.png / icon.svg: These two files (a 1024×1024 PNG and transparent SVG) are used in various places throughout Ferdi to represent your recipe. If you’re making a recipe for a large company, they’re likely to have a helpful “Brand assets” page on their site. For example, Facebook Messenger provides both the necessary files. If you can’t find any prepared downloads, you may need to find the resources elsewhere. I found Vecta extremely helpful!\n\npackage.json: This file contains the metadata about your recipe. You’ll almost certainly just need to update the id, name, description, author and serviceURL to more appropriate values. You may also need to update hasNotificationSound to avoid double notifying users. There’s a detailed explanation of all possible fields on the Ferdi wiki.\n\nindex.js: This file contains the JavaScript that Ferdi itself should run, NOT on the site itself. This probably doesn’t need anything more than the minimal configuration:\n\n\"use strict\";\nmodule.exports = Franz =&gt; Franz;\n\n\nwebview.js: This is the file that handles the JavaScript for actually listening for notifications. Whilst this will be different for every site, essentially the goal is to find an HTML element on the screen that contains the number of notifications. The number of notifications can then be pulled from this element. For Nextdoor, there is a notification-badge element that only appears if there are unread notifications. If the element isn’t present, there are 0 notifications.\n\nThis is the Nextdoor script, it needs to be customised (via trial and error in the Chrome console) for your recipe!\n\n\"use strict\";\n\nmodule.exports = Franz =&gt; {\n  const getMessages = function getMessages() {\n    var unread = 0\n    const notificationBadge = document.getElementsByClassName('notification-badge')[0]\n    if (notificationBadge != undefined) {\n        unread = notificationBadge.innerText;\n    }\n    Franz.setBadge(parseInt(unread, 10));\n  };\n\n  Franz.loop(getMessages);\n};\n\n\nLoading into Ferdi\n\n\nNow that you have the first draft of your custom recipe inside the dev folder, it can be loaded into Ferdi:\n\n\n  Restart Ferdi.\n  Open Ferdi settings.\n  Go to “Available services” tab.\n  Go to “Custom Services” tab.\n  Your recipe should show up under “Community 3rd Party Recipes”, click it and it’ll be added like any other service!\n\n\nPublishing your Ferdi recipe\n\nTo get your new recipe into the main Ferdi repository to others can use it, it has to be properly published, packaged, and reviewed.\n\nUploading recipe repository\n\nYour recipe has to be uploaded to a public GitHub repository, there’s many guides if you haven’t done this before. Your repository should look like this once done.\n\nRunning packaging scripts\n\n\n  Fork the Ferdi recipes repository (here is a guide if needed).\n  Check out your forked repository.\n  If you don’t have Yarn already installed (I didn’t), install it with the default options.\n  Open a terminal / Powershell / Command prompt in the /scripts/ folder of your forked repo.\n  Run yarn install to run all of the dependencies needed for prepare the packaging script. You should see a “Done” message.\n  Run yarn github &lt;your recipe repo's URL&gt; to package your recipe. You should see a “Done” message again.\n  Your fork of the Ferdi recipes repository should now have 6 new files (your recipe), and 1 modified file (the metadata storage). This is how it looks in GitKraken.\n  Commit these files, then push your repository.\n\n\nRaising PR\n\nYou now have a version of Ferdi’s recipes repo with your changes, which need to be approved.\n\nJust raise a PR against the repo (something like this, here’s a guide), and one of the project’s maintainers will take a look and check your work. Any issues will be raised, or the code will be merged.\n\nYou’ve contributed to an open source project, congrats!\n"
    } ,
  
    {
      "tags"     : "Chat, Ferdi, Messaging, Recommendation, WFH",
      "title"    : "Recommendation: Ferdi, the messaging service aggregator",
      "excerpt"  : "Most of us have a surprisingly wide variety of messaging services installed on our laptops / desktops that we use for different types of communication. Between WhatsApp, Teams, Discord, Slack, Messenger etc, it’s easy to lose track of them all!\n",
      "url"      : "/recommendation-ferdi-the-messaging-service-aggregator/",
      "date"     : "Apr 10, 2020",
      "content"  : "Most of us have a surprisingly wide variety of messaging services installed on our laptops / desktops that we use for different types of communication. Between WhatsApp, Teams, Discord, Slack, Messenger etc, it’s easy to lose track of them all!\n\nConfiguring each on your machine usually requires installing a program, sorting out notifications, keeping it updated, and hoping there’s no security holes. To solve this, I use the open source “messaging browser” Ferdi, that provides all my messaging services in one program, letting them be controlled easily.\n\nThis post isn’t sponsored whatsoever, it’s a personal recommendation!\n\nFerdi Overview\n\nFerdi is based on Franz, a widely used messaging service aggregator, and is built for Mac, Windows, and Linux. I used Franz for many years, but after it started adding artificial delays, nagging for referrals, and making previously free features paid for I looked elsewhere. The number of improvements is honestly a bit staggering!\n\nFerdi lets you combine all of your messaging services into one, behaving essentially like a browser with a tab for each. In doing so, it lets you fine tune the notifications for each service, create “workspaces” for work and home, and take back control of your messaging.\n\nJust like Franz, Ferdi is open source and actively developed. However, by working on a donation model it provides a much more user friendly experience, for free. Ferdi is also part of the Open Collective, openly sharing their costs &amp; donations.\n\nFeatures\n\n\nPersonally, the main appeal of Ferdi is the straightforward and simple approach to managing my services. However, it has a lot of advanced features for those users that want them, I’ll run through a few:\n\nWorkspaces: By having a “Work” and “Home” workspace (collection of services), you can help keep your personal and professional lives separate.\n\nOne-click mute: When working from home, you’ll often need to share your screen. Being able to mute all your services (including that WhatsApp group!) with a single click / shortcut helps avoid any embarrassment.\n\nCustom services: Want to add your company’s bespoke messaging system, with full notification support? Sure, no problem!\n\nTo do list: You can add your preferred to do list, making sure it is available at all times.\n\nPrivacy: Whilst your personal data is never sent to Ferdi, it even lets you configure the server your user preferences are sent to. For example, you may want to store this data on your own in-house server. As an icing on the cake, it’s also possible to configure Franz to use a proxy for any of the services, making it more secure than a normal browser.\n\nCustom CSS / JS: Want to customise WhatsApp’s appearance? Add some extra functionality into Slack? No problem, just configure custom CSS / JS to run, and Franz will inject them for you!\n\nMessaging Services\n\n\nFerdi supports ~100 services out of the box, which is made essentially infinite by the support for custom sites.\n\nI personally use the Messenger, WhatsApp, LinkedIn, Instagram, Discord, and Slack (4x) services pretty much daily, covering every place I talk to other people!\n\nDrawbacks\n\nAs much as I love Ferdi, it’s only fair to discuss drawbacks. Luckily, there aren’t many!\n\nThe only notable one for me has to be the memory usage. As it’s essentially Chrome with 9 tabs, it has the same RAM hunger that Chrome does.\n\nFor my relatively high-end desktop, this means ~5% of my CPU and ~2GB of RAM is used. This can be reduced by letting Ferdi disable background messaging services, but it seems reasonable to me.\n\n\n\nSummary\n\nTo put it simply: I love Ferdi. It does exactly what I want to, costs nothing, lets me keep my privacy. Additionally, it has plenty of customisation if I need it in the future.\n\nI’ve also been enjoying their “less corporate” attitude. I reached out to their Twitter to point out a typo and I had a fix &amp; a kind response in half hour!\n\nI’d strongly recommend giving it a go, and seeing if you think it could fit into your work habits. If you encounter any problems or have ideas, it’s open source so you can make suggestions! It’s how almost all of the current great features have been added.\n"
    } ,
  
    {
      "tags"     : "AppBundles, bash, CI, Travis, Tutorial",
      "title"    : "Uploading an app bundle to Google Play Internal App Sharing from Travis CI",
      "excerpt"  : "In a post towards the end of last year, I explained how to generate app bundles on your CI server (in my case Travis). Now they’re being generated, the next step is to send them somewhere!\n",
      "url"      : "/uploading-an-app-bundle-to-google-play-internal-app-sharing-from-travis-ci/",
      "date"     : "Feb 18, 2020",
      "content"  : "In a post towards the end of last year, I explained how to generate app bundles on your CI server (in my case Travis). Now they’re being generated, the next step is to send them somewhere!\n\nGoogle Play Internal App Sharing is my chosen destination, since that allows QAs to easily download and test the app bundle.\n\nUpdate: If using Gradle plugin 3.5.0+, the app bundle will be generated at app-&lt;variant&gt;.aab (e.g. app-debug.aab) instead of app.aab. The following tutorial has been left unchanged, make sure to edit your script if using a later Gradle plugin version!\n\nThis post assumes you already have a custom bash script running on your CI, and are already generating app bundles. If that isn’t the case, please read the previous post in the series (or view the end code). You can view the end result of this post as a gist.\n\nWhilst the uploading process is simple, the biggest challenge is actually authenticating with Google! We’ll cover that before diving into the code itself.\n\nCreating a Google service account\n\nTo create a service account, you’ll need access to Google Play Console and Google Developers Console. On Google Play Console, you’ll need to make a service account. There are official instructions, but there’s a few steps missing.\n\n\n  Go to Settings -&gt; Developer account -&gt; API access, and click “Create service account” (screenshot).\n  Click the “Google API console” link (screenshot), then click “Create service account” again(screenshot).\n  Fill in the basic details, to help remember what the account is for (screenshot).\n  Give your new account the “Firebase App Distribution Admin” role (screenshot).\n  Create a key for the new account, and download it in JSON format (screenshot). This will download a JSON file (screenshot).\n  Finally, your new service account will show up on Google Play Console, press “Grant access” (screenshot).\n\n\nNext, we need to prepare our JSON file for our CI server.\n\nEncrypting your config file with Travis CI\n\nSince our JSON file contains sensitive information, we don’t want it to be stored directly in our repo. Whilst this is essential for a public repository, it’s a good habit for private repos too. Luckily, Travis has built-in support for file encryption!\n\nThese instructions are for a Mac, but a similar process will work on a Windows machine. Assume the service account config has been renamed to serviceaccount.json and placed in /scripts/:\n\n\n  Install Travis command line with gem install travis.\n  Log in to your GitHub account via Travis. You can either do this by entering your username, password, and 2FA code using travis login, or by using an application password.\n  Make sure your Terminal is in your project root (so Travis knows which account to store the file against), then enter travis encrypt-file /scripts/serviceaccount.json.\n  This will make a new file /scripts/serviceaccount.json.enc, and output the decryption command to add to the before_install part of your .travis.yml. It will look something like:\n\n\nopenssl aes-256-cbc -K $encrypted_def446eb3abc_key -iv $encrypted_def446eb3abc_iv -in scripts/serviceaccount.json.enc -out scripts/serviceaccount.json -d\n\n\nThat’s it! Make sure to delete your original file and commit your encrypted file.\n\nOnce that’s done, sending the app bundle itself is pretty easy. To start off with and help explain the overall flow, here’s the main function.\n\nPreparing overall script structure\n\nFor this script, the overall control is handled by uploadToInternalAppSharing, which calls a few functions we’ll be defining shortly. There’s also a parameter check at the very start (as with all other functions in this post) and a few comments, just to help out any future maintainers.\n\nfunction uploadToInternalAppSharing {\n    if (($# != 2)); then echo \"Please pass the bundle path and service account JSON location!\"; exit 2; fi\n    BUNDLE_LOCATION=\"${1}app.aab\"\n    AUTH_LOCATION=\"${2}\"\n\n    # Parse service account JSON for authentication information\n    SERVICE_ACCOUNT_CONFIG=$(&lt;${AUTH_LOCATION})\n    AUTH_SERVER=$(echo ${SERVICE_ACCOUNT_CONFIG} | jq -r '.token_uri')\n    AUTH_EMAIL=$(echo ${SERVICE_ACCOUNT_CONFIG} | jq -r '.client_email')\n    AUTH_KEY=$(echo ${SERVICE_ACCOUNT_CONFIG} | jq -r '.private_key')\n    echo \"Retrieved service account from JSON!\"\n\n    # Generate JWT from authentication information\n    JWT=$(getJwt \"$AUTH_SERVER\" \"$AUTH_EMAIL\" \"$AUTH_KEY\")\n    echo \"Generated JWT!\"\n\n    # Use JWT to authenticate with Google and retrieve an access token\n    ACCESS_TOKEN=$(getAccessToken \"$AUTH_SERVER\" \"$JWT\")\n    echo \"Generated access token!\"\n\n    # Use access token to upload app bundle to Google Play Internal App Sharing\n    URL=$(uploadBundle \"$ACCESS_TOKEN\" \"$BUNDLE_LOCATION\")\n    echo \"Uploaded app bundle to ${URL}\"\n}\n\n\nNow that’s in place, we need to actually implement the functionality! The rest of this post will walk through the above function, and the calls it makes.\n\nDecrypt your encrypted file\n\nInside your .sh script (triggered in your .travis.yml), specify your decrypted auth file’s location:\n\nAUTH_LOCATION=${TRAVIS_BUILD_DIR}/scripts/serviceaccount.json\n\n\nNext, pass this (and your bundle’s location) into uploadToInternalAppSharing so the file can be read:\n\nSERVICE_ACCOUNT_CONFIG=$(${AUTH_LOCATION})\n\n\nNext, retrieve the necessary variables from this file. In this case, that’s the token URI, email, and private key:\n\nAUTH_SERVER=$(echo ${SERVICE_ACCOUNT_CONFIG} | jq -r '.token_uri')\nAUTH_EMAIL=$(echo ${SERVICE_ACCOUNT_CONFIG} | jq -r '.client_email')\nAUTH_KEY=$(echo ${SERVICE_ACCOUNT_CONFIG} | jq -r '.private_key')\n\n\nWe now pass these 3 variables into our getJwt function, storing the result: JWT=$(getJwt \"$AUTH_SERVER\" \"$AUTH_EMAIL\" \"$AUTH_KEY\").\n\nCreate JWT\n\nWhilst the following block of code does look a bit intimidating, it’s just performing the necessary manipulations to make a JWT (JSON Web Token). You can find more information about JWTs and validate their contents at jwt.io. We’ll be using them to prove to Google that we are allowed to act on the behalf of the service account we created\n\nThe output of this function should be a fairly lengthy string of characters, which can be used for the next step. Note that the EOF must be without any indentation, no matter how tidy you usually keep your code!\n\nfunction getJwt {\n    if (($# != 3)); then echo \"Please pass the auth server, auth email, and auth key!\"; exit 2; fi\n    AUTH_SERVER=$1\n    AUTH_EMAIL=$2\n    AUTH_KEY=$3\n\n    # Create JWT header\n    JWT_HEADER=$(echo -n '{\"alg\":\"RS256\",\"typ\":\"JWT\"}' | openssl base64 -e)\n\n    # Create JWT body\n    JWT_BODY=$(cat &lt;&lt;EOF\n    {\n        \"aud\": \"${AUTH_SERVER}\",\n        \"iss\": \"${AUTH_EMAIL}\",\n        \"scope\": \"https://www.googleapis.com/auth/androidpublisher\",\n        \"exp\": $(($(date +%s)+300)),\n        \"iat\": $(date +%s)\n    }\nEOF\n    )\n    JWT_BODY_CLEAN=$(echo -n \"$JWT_BODY\" | openssl base64 -e)\n\n    # Create complete payload\n    JWT_PAYLOAD=$(echo -n \"$JWT_HEADER.$JWT_BODY_CLEAN\" | tr -d '\\n' | tr -d '=' | tr '/+' '_-')\n\n    # Create JWT signature\n    JWT_SIGNATURE=$(echo -n \"$JWT_PAYLOAD\" | openssl dgst -binary -sha256 -sign &lt;(printf '%s\\n' \"$AUTH_KEY\") | openssl base64 -e)\n    JWT_SIGNATURE_CLEAN=$(echo -n \"$JWT_SIGNATURE\" | tr -d '\\n' | tr -d '=' | tr '/+' '_-')\n\n    # Combine JWT payload and signature\n    echo ${JWT_PAYLOAD}.${JWT_SIGNATURE_CLEAN}\n}\n\n\nOnce we have our JWT, it can be passed to our getAccessToken function, again saving the result: ACCESS_TOKEN=$(getAccessToken \"$AUTH_SERVER\" \"$JWT\")\n\nRetrieve auth token\n\nWe now need to make a call to the auth server we retrieved from our service account config earlier. We’re going to send it our JWT, and hopefully get back a token we can use to send content for the next few minutes. Notice the same jq -r technique as earlier used again.\n\nfunction getAccessToken {\n    if (($# != 2)); then echo \"Please pass the auth server and JWT!\"; exit 2; fi\n    AUTH_SERVER=$1\n    JWT=$2\n\n    # Send JWT to auth server\n    HTTP_RESPONSE=$(curl --silent --write-out \"HTTPSTATUS:%{http_code}\" \\\n      --header \"Content-type: application/x-www-form-urlencoded\" \\\n      --request POST \\\n      --data \"grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&amp;assertion=$JWT\" \\\n      \"$AUTH_SERVER\")\n\n    # Parse auth server response for body and status\n    HTTP_BODY=$(echo ${HTTP_RESPONSE} | sed -e 's/HTTPSTATUS\\:.*//g')\n    HTTP_STATUS=$(echo ${HTTP_RESPONSE} | tr -d '\\n' | sed -e 's/.*HTTPSTATUS://')\n\n    # Check response status for success, and retrieve access token if possible\n    if [[ ${HTTP_STATUS} != 200 ]]; then\n        echo -e \"Create access token failed.\\nStatus: $HTTP_STATUS\\nBody: $HTTP_BODY\\nExiting.\"\n        exit 1\n    fi\n    echo $(echo ${HTTP_BODY} | jq -r '.access_token')\n}\n\n\nFinally we’re ready to actually send our bundle! We do this by sending our access token (and bundle location) to our new uploadBundle function. We keep track of the result as usual: URL=$(uploadBundle \"$ACCESS_TOKEN\" \"$BUNDLE_LOCATION\")\n\nUpload to Internal App Sharing\n\nThis function is very similar to the access token fetching, except this time we’re posting our bundle instead of our JWT. We’re also going to use --progress-bar for a nice visual way of keeping track of upload process, very useful when a bundle gets into the 10s of MB. Don’t forget to use your own package name!\n\nThis will finally return the URL we’re after, which testers can use to download the app.\n\nfunction uploadBundle {\n    if (($# != 2)); then echo \"Please pass the access token and bundle location!\"; exit 2; fi\n    ACCESS_TOKEN=$1\n    BUNDLE_LOCATION=$2\n\n    # Send app bundle and access token to internal app sharing\n    PACKAGE=\"uk.co.jakelee.examplepackage\"\n    HTTP_RESPONSE=$(curl --write-out \"HTTPSTATUS:%{http_code}\" \\\n      --header \"Authorization: Bearer $ACCESS_TOKEN\" \\\n      --header \"Content-Type: application/octet-stream\" \\\n      --progress-bar \\\n      --request POST \\\n      --upload-file ${BUNDLE_LOCATION} \\\n      https://www.googleapis.com/upload/androidpublisher/v3/applications/internalappsharing/${PACKAGE}/artifacts/bundle?uploadType=media)\n\n    # Parse internal app sharing response for body and status\n    HTTP_BODY=$(echo ${HTTP_RESPONSE} | sed -e 's/HTTPSTATUS\\:.*//g')\n    HTTP_STATUS=$(echo ${HTTP_RESPONSE} | tr -d '\\n' | sed -e 's/.*HTTPSTATUS://')\n\n   # Check response status for success, and retrieve download URL if possible\n   if [[ ${HTTP_STATUS} != 200 ]]; then\n       echo -e \"Upload app bundle failed.\\nStatus: $HTTP_STATUS\\nBody: $HTTP_BODY\\nExiting.\"\n       exit 1\n   fi\n   echo $(echo ${HTTP_BODY} | jq -r '.downloadUrl')\n}\n\n\nNow, when this script runs on your CI, you should see something like:\n\n\n\nIf anything didn’t quite work out, the gist of this post may help! Otherwise, feel free to leave a comment and I’ll help out.\n\nAdding uploaders and testers\n\nBefore these internal apps can actually be used, we need to set up permissions for them. This is done from the application’s page on Google Play Console, then Development Tools -&gt; Internal App Sharing.\n\nOn this page, select any other groups of people you’d like to be able to upload bundles manually, and any groups of QA / other testers (screenshot).\n\nNow, when one of your testers clicks the link generated above on an account with app sharing enabled, they’ll be prompted to install the app. For information on enabling app sharing and more information on the system, Google’s documentation is pretty helpful.\n\nNext steps\n\nWhilst it’s excellent that testers can now download the app by looking at Travis logs, obviously this isn’t an ideal solution. The next post in this series will cover notifying QA that a new build is available (likely through Slack, or email).\n\nA possible improvement would be notifying developers if a part of the process fails, and perhaps retrying any failed attempts. However, in my experience the steps have been very reliable so this hasn’t been necessary.\n\nIt’s also very important to remember these builds will only be available for 60 days, and won’t natively mention anything about which branch they’re from, who made them, etc. As such, this has to be handled via alternative systems for now.\n\nReferences\n\n\n  Encrypting files: https://docs.travis-ci.com/user/encrypting-files/\n  Share app bundles and APKs internally: https://support.google.com/googleplay/android-developer/answer/9303479?hl=en-GB\n  Internal app sharing artifacts: https://developers.google.com/android-publisher/api-ref/internalappsharingartifacts\n  Google PlayStore internal app sharing: https://www.brightec.co.uk/blog/google-playstore-internal-app-sharing\n  Google PlayStore and automated deployment: https://www.brightec.co.uk/blog/google-playstore-and-automated-deployment\n  Google PlayStore automated deployment with AAB: https://www.brightec.co.uk/blog/google-playstore-automated-deployment-aab\n\n"
    } ,
  
    {
      "tags"     : "APK, AppBundles, CI, Travis",
      "title"    : "How to create an app bundle (and APK) on Travis / CI server",
      "excerpt"  : "App bundles are one of my 5 Android techniques for 2020, and with good reason: they’re a low effort way of drastically reducing app size. Surprisingly, we also noticed faster times creating an app bundle then an APK than creating an APK directly. Of course, moving away from APKs is trickier if you have a complicated multi-stage build process involving QA or deployment!\n",
      "url"      : "/creating-an-app-bundle-and-apk-on-travis-ci-server/",
      "date"     : "Dec 23, 2019",
      "content"  : "App bundles are one of my 5 Android techniques for 2020, and with good reason: they’re a low effort way of drastically reducing app size. Surprisingly, we also noticed faster times creating an app bundle then an APK than creating an APK directly. Of course, moving away from APKs is trickier if you have a complicated multi-stage build process involving QA or deployment!\n\nCurrently I am transitioning a large app slowly from APKs to app bundles whilst retaining compatibility with our existing processes. For now this means generating both app bundles and APKs. Whilst creating both isn’t especially tricky, the detailed explanations in this post should make it easier to implement into Travis.\n\nUpdate: If using Gradle plugin 3.5.0+, the app bundle will be generated at app-&lt;variant&gt;.aab (e.g. app-debug.aab) instead of app.aab. The following tutorial has been left unchanged, make sure to edit your script if using a later Gradle plugin version!\n\nThe plan\n\nOur approach is going to consist of 4 steps:\n\n\n  Preparing Travis to use a build script\n  Making an app bundle for our app\n  Downloading bundletool, so we can…\n  …generate a universal APK from our app bundle\n\n\nIf you’d like to see a finished script of this post (recommended), it’s available as a Gist: https://gist.github.com/JakeSteam/eacc45ddd0db942d6902150f09dfa39f\n\nPreparing Travis / CI config\n\nBefore we write anything, we need to make our CI config (e.g. .travis.yml) able to run a shell script! Otherwise, our build config is going to get very messy. These steps are going to vary a little bit between CIs, but should be pretty similar.\n\n\n  Before anything else, make sure the build scripts can be executed by changing their permissions (assuming they’re in /build-scripts/):\n\n\n    before_install: # Make sure build scripts can be executed\n          - chmod 755 build-scripts/*.sh\n\n\n  Next, add your script to the script step, passing the built-in build directory variable:\n\n\n    script: # Runs build script\n      - build-scripts/travis_build.sh $TRAVIS_BUILD_DIR\n\n\nOur CI is now going to run build-scripts/travis_build.sh, so let’s make that file and make it do something!\n\nMaking an app bundle\n\nThis is amazingly simple, we just need to run the gradle task for bundle generation inside our travis_build.sh file:\n\n./gradlew app:bundleDebug\n\n\nIf you’re using build variants (e.g. prodDebug), you’ll need to do app:bundleProdDebug instead. This would also be a good place to do lintDebug, ktlint, or any other pre-build checks by adding them to the list of gradle tasks.\n\nDownloading bundletool\n\nTo convert our app bundle into a universal APK (an APK that can be installed on any device), we’ll need bundletool. This is just a case of curling it:\n\ncurl -O -L \"https://github.com/google/bundletool/releases/download/0.11.0/bundletool-all-0.11.0.jar\"\n\n\nUsing bundletool to create a universal APK\n\nTo create our universal APK we’ll need our keystore information. This can be hardcoded, passed in, stored in environment variables, retrieved from a remote server etc, but we’ll be keeping it simple. We’re also storing a debug keystore in our repo for simplicity, and passing in the bundle &amp; output locations. Travis’ build directory is passed in from our build config.\n\n# Get the build directory from build config\nTRAVIS_BUILD_DIR=$1\n\n# Use bundletool to create universal .apks zip\njava -jar bundletool-all-0.11.0.jar build-apks \\\n    --mode=universal \\\n    --bundle=${TRAVIS_BUILD_DIR}/app/build/outputs/bundle/prodDebug/app.aab \\\n    --output=${TRAVIS_BUILD_DIR}/app/build/outputs/bundle/prodDebug/app.apks \\\n    --ks=${TRAVIS_BUILD_DIR}/app/build-extras/debug.keystore \\\n    --ks-pass=pass:android \\\n    --ks-key-alias=androiddebugkey \\\n    --key-pass=pass:android;\n\n\nBundletool actually creates an .apks file, a zip file of our universal APK. We can get our actual APK with a quick unzip into a new unzipped folder:\n\nunzip ${TRAVIS_BUILD_DIR}/app/build/outputs/bundle/prodDebug/app.apks -d ${TRAVIS_BUILD_DIR}/app/build/outputs/bundle/prodDebug/unzipped;\n\n\nAnd that’s it! We now have our universal APK at ${TRAVIS_BUILD_DIR}/app/build/outputs/bundle/prodDebug/unzipped/universal.apk, ready to be sent to wherever wants an APK.\n\nTidying up\n\nWhilst the above approach does achieve the goal, the code is pretty messy and hard coded. Extracting variables and making the code more generic will let us use it for debug and release builds, as well as making it easier to modify.\n\nExtracting variables\n\nInside our travis_build.sh script, we should extract all of our file locations and keystore information. Once this is done, it will be possible to pass the variables to a generic function that can handle any build type. For example:\n\n# Debug build variables\nDEBUG_BUNDLE_PATH=${TRAVIS_BUILD_DIR}/app/build/outputs/bundle/prodDebug/\nDEBUG_KEYSTORE_PATH=${TRAVIS_BUILD_DIR}/app/build-extras/debug.keystore\nDEBUG_KEYSTORE_PASSWORD=android\nDEBUG_KEYSTORE_ALIAS=androiddebugkey\nDEBUG_KEYSTORE_KEY_PASSWORD=android\n\n# Release build variables\nRELEASE_BUNDLE_PATH=${TRAVIS_BUILD_DIR}/app/build/outputs/bundle/prodRelease/\nRELEASE_KEYSTORE_PATH=${TRAVIS_BUILD_DIR}/app/build-extras/upload-keystore.jks\nRELEASE_KEYSTORE_PASSWORD=mypassword\nRELEASE_KEYSTORE_ALIAS=uploadkey\nRELEASE_KEYSTORE_KEY_PASSWORD=mykeypassword\n\n\nExtracting into functions\n\nConverting our script into functions will simplify the overall logic, and help clarify the code’s meaning. I chose to split my code into “bundle generating” and “bundle to apk conversion” functions. The converter also includes a quick check for the number of parameters passed:\n\nfunction compileAndTestDebugBundle {\n    echo \"Compiling and testing a debug bundle!\"\n    ./gradlew app:bundleDebug\n}\n\nfunction convertBundleToApk {\n    # Check all necessary arguments have been passed\n    if [[ \"$#\" -eq 5 ]]; then\n        echo \"Converting bundle to APK!\"\n    else\n        echo \"Make sure you pass in a bundle path, and all 4 keystore values!\"\n        exit 1\n    fi\n\n    # Download bundletool\n    curl -O -L \"https://github.com/google/bundletool/releases/download/0.11.0/bundletool-all-0.11.0.jar\"\n\n    # Use bundletool to create universal .apks zip\n    java -jar bundletool-all-0.11.0.jar build-apks \\\n        --mode=universal \\\n        --bundle=${1}app.aab \\\n        --output=${1}app.apks \\\n        --ks=${2} \\\n        --ks-pass=pass:${3} \\\n        --ks-key-alias=${4} \\\n        --key-pass=pass:${5};\n\n    # Unzip .apks zip into /unzipped\n    unzip ${1}app.apks -d ${1}unzipped;\n}\n\n\nNow, we can just call our functions (with the parameters) to perform the task, making the code’s intention much more obvious. Making a release build is as simple as passing different parameters, easy!\n\ncompileAndTestDebugBundle;\nconvertBundleToApk ${DEBUG_BUNDLE_PATH} ${DEBUG_KEYSTORE_PATH} ${DEBUG_KEYSTORE_PASSWORD} ${DEBUG_KEYSTORE_ALIAS} ${DEBUG_KEYSTORE_KEY_PASSWORD}\n\n\nSecuring passwords\n\nWhilst our approach so far works well, it isn’t particularly secure. Our keystore passwords are in our build config, meaning they’re visible to anyone who can see our CI logs or repository. Travis’ encrypted environment variables are a great solution to this. They encrypt your password (e.g. KEYSTORE_PASSWORD and KEYSTORE_KEY_PASSWORD, and only provide it to you during a build (they can be retrieved though!). This can then be passed to your script and used by changing the build config to:\n\nscript: # Runs build script\n  - build-scripts/travis_build.sh $TRAVIS_BRANCH $KEYSTORE_PASSWORD $KEYSTORE_KEY_PASSWORD\n\n\nAnd your variable definitions to:\n\nRELEASE_KEYSTORE_PASSWORD=$2\nRELEASE_KEYSTORE_KEY_PASSWORD=$3\n\n\nNext steps\n\nWhilst the results of this post are enough to create app bundles and APKs, there’s always improvements to be made. For example, the functions could be extracted to a new .sh file, then included in travis_build.sh.\n\nYou could also perform a release build for specific branches, by passing the TRAVIS_BRANCH environment variable from the Travis config. This value can then be used in a simple if statement to create a build:\n\nif [[ ${TRAVIS_BRANCH} == \"dev\" ]]; then\n    compileAndTestReleaseBundle;\n    convertBundleToApk ${RELEASE_BUNDLE_PATH} ${RELEASE_KEYSTORE_PATH} ${RELEASE_KEYSTORE_PASSWORD} ${RELEASE_KEYSTORE_ALIAS} ${RELEASE_KEYSTORE_KEY_PASSWORD}\n    uploadToDeployGate;\nelse\n    compileAndTestDebugBundle;\n    convertBundleToApk ${DEBUG_BUNDLE_PATH} ${DEBUG_KEYSTORE_PATH} ${DEBUG_KEYSTORE_PASSWORD} ${DEBUG_KEYSTORE_ALIAS} ${DEBUG_KEYSTORE_KEY_PASSWORD}\n    uploadToDeployGate;\nfi\n\n\nFinally, the next step for me will be moving away from APKs completely, by using Google Play Internal App Sharing for QA. The article for implementing this is now available.\n\nPS: Just in case anyone missed it, here’s the outcome of this post: https://gist.github.com/JakeSteam/eacc45ddd0db942d6902150f09dfa39f\n\nPPS: Happy holidays!\n"
    } ,
  
    {
      "tags"     : "ccrypt, CI, Travis",
      "title"    : "Retrieving forgotten environment variables from Travis CI",
      "excerpt"  : "When using a CI server, you’ll often need a way to use highly sensitive strings (e.g. signing keys, API keys, passwords), whilst minimising who has access to them. Travis CI solves this using encrypted environment variables, encrypting your variables using a private key only Travis has access to. These encrypted values are then stored in your .travis.yml.\n",
      "url"      : "/retrieving-forgotten-environment-variables-from-travis-ci/",
      "date"     : "Dec 18, 2019",
      "content"  : "When using a CI server, you’ll often need a way to use highly sensitive strings (e.g. signing keys, API keys, passwords), whilst minimising who has access to them. Travis CI solves this using encrypted environment variables, encrypting your variables using a private key only Travis has access to. These encrypted values are then stored in your .travis.yml.\n\nThis means nobody sees your plaintext string except Travis, and it is never sent between servers. The downside of this? If you lose the secret string, only Travis knows what it is!\n\nWhen transitioning from APKs to app bundles recently (article soon!), I discovered our keystore’s password wasn’t stored anywhere besides Travis. The entire app being dependent on our CI staying up scared me! As such, I decided to extract the plaintext value to store in the same secure area as other company passwords.\n\nSince Travis (correctly) tries very hard to stop you getting these variables back out, you’ll need to take a roundabout approach. I also didn’t want our password ever being displayed in the logs, or sent over the internet in plaintext.\n\nThe plan\n\n\n  Create a new secure variable as an encryption key.\n  During a build decrypt our target variable into a file, then encrypt the file using our new encryption key.\n  Transfer this encrypted file off the CI server using file.io.\n  Download it, then decrypt using the encryption key we created in step 1.\n\n\nPreparing Travis CI\n\nBefore running the script, you will need to add a new environment variable to Travis called ENC_KEY, and make it only available on your current branch. It should end up looking like this:\n\n\n\nNote: It’s good practice to always limit the branches your environment variables can run on.\n\nPreparing the build config\n\nNext, add the following to your .travis.yml build config. Don’t forget to replace:\n\n\n  MY_VARIABLE (two times) with your target encrypted variable’s name.\n  arandomfilename (three times) with a string of your choice.\n\n\ninstall:\n  - sudo apt-get install -y ccrypt\n  - echo MY_VARIABLE = $MY_VARIABLE &gt; arandomfilename.txt\n  - ccencrypt arandonfilename.txt -K $ENC_KEY\n  - curl -F'file=@arandomfilename.txt.cpt' https://file.io\n\n\nThis script installs ccrypt, puts our decrypted variable into a file, encrypts the file, and hosts it.\n\nRunning the script\n\n\n  Commit your build config changes.\n  Push the branch.\n  You should now see a response with a URL after your last cURL statement, e.g:\n\n\n$ curl -F'file=@arandomfilename.txt.cpt' https://file.io\n{\"success\":true,\"key\":\"he5h9\",\"link\":\"https://file.io/he5h9\",\"expiry\":\"14 days\"}\n\n\nNote: This line of the log may be hidden by default by Travis, make sure to click any “expand” arrows.\n\nRetrieving the value\n\n\n  First, you need to download your encrypted file from the returned URL using curl (e.g. curl -O https://file.io/he5h9) or by opening it in a browser.\n  Next, you need ccrypt installed to decrypt it (e.g. brew install ccrypt).\n  Finally, decrypt it (e.g. ccrypt -d arandomfile.cpt).\n  You now have a text file containing your target value!\n\n\nAdditional notes\n\nWhilst the ability to retrieve a supposedly secure variable may seem concerning, it’s important to note this is only possible if you have push access to the repo. Travis also has the ability to only allow variables to be accessed from specific branches (e.g. master), which should be used when possible.\n\nAlso, whilst transferring even an encrypted value off-site may seem scary, file.io has extra protection. Once your file has been downloaded once, it can never be downloaded again. Thus, there’s no risk of someone else randomly stumbling across the file.\n\nFinally, file hosts tend to come and go pretty quickly. If file.io no longer exists, any other command line based upload service will work!\n\nThis article is based on an excellent (but outdated) article by Matthew Twomey, which also covers how to avoid needing a third party host at all.\n"
    } ,
  
    {
      "tags"     : "Dependency, Gradle, Modules",
      "title"    : "How to see all dependencies in a multi-module Android app",
      "excerpt"  : "Recently at work, I needed to provide a list of all dependencies / external libraries used by an app. Requests like these are inevitable when working on bigger apps, especially with legislation like GDPR.\n",
      "url"      : "/how-to-see-all-dependencies-in-a-multi-module-android-app/",
      "date"     : "Dec 16, 2019",
      "content"  : "Recently at work, I needed to provide a list of all dependencies / external libraries used by an app. Requests like these are inevitable when working on bigger apps, especially with legislation like GDPR.\n\nWhilst it’s easy to check your app’s Gradle file to see dependencies, this only works for that module. For a multi module project however, there must be an easier way than opening every module’s Gradle file and merging them in a text file!\n\nTree view\n\nIf you need a list of all dependencies, and all of their dependencies, and all of… etc, you’ll want a tree view. This is useful for checking the same version of common libraries are being used throughout your app. The downside? It’s massive! Including a single AndroidX library can add 20 entries to this list.\n\nRunning ./gradlew app:dependencies in the terminal will produce something similar to:\n\n...\n| +--- androidx.preference:preference:1.1.0\n| | +--- androidx.appcompat:appcompat:1.1.0 (*)\n| | +--- androidx.core:core:1.1.0 (*)\n| | +--- androidx.fragment:fragment:1.1.0 (*)\n| | +--- androidx.recyclerview:recyclerview:1.0.0 (*)\n| | +--- androidx.annotation:annotation:1.1.0\n| | \\--- androidx.collection:collection:1.0.0 -&gt; 1.1.0 (*)\n| +--- androidx.lifecycle:lifecycle-extensions:2.1.0\n| | +--- androidx.lifecycle:lifecycle-runtime:2.1.0 (*)\n| | +--- androidx.arch.core:core-common:2.1.0 (*)\n| | +--- androidx.arch.core:core-runtime:2.1.0 (*)\n| | +--- androidx.fragment:fragment:1.0.0 -&gt; 1.1.0 (*)\n...\n\n\nFlat view\n\nIf however, you just want a simple list of all dependencies, ./gradlew app:androidDependencies is best. This will list any jar files, submodules, and libraries used in your app.\n\n+--- :ui (variant: debug)\n+--- me.tatarka.bindingcollectionadapter2:bindingcollectionadapter-recyclerview:3.0.0@aar\n+--- me.tatarka.bindingcollectionadapter2:bindingcollectionadapter:3.0.0@aar\n+--- androidx.databinding:databinding-adapters:3.4.1@aar\n+--- androidx.databinding:databinding-runtime:3.4.1@aar\n+--- androidx.databinding:databinding-common:3.4.1@jar\n+--- :dataaccess\n+--- :dependencies:exoplayer\n+--- :dependencies:gson\n+--- :dependencies:okhttp\n+--- au.com.gridstone.rxstore:rxstore-kotlin:6.0.0@jar\n+--- org.jetbrains.kotlin:kotlin-stdlib:1.3.40@jar\n+--- com.squareup.dagger:dagger:1.2.2@jar\n+--- io.reactivex.rxjava2:rxandroid:2.1.1@aar\n\n\nIf this list is to be shared with a non-technical audience, I recommend opening your favourite text editor and:\n\n\n  Find and replacing @aar and @jar with an empty string.\n  Next, removing the +--- from the start of each line.\n  Next, removing all submodules, as they’re not external dependencies.\n  (Optionally) removing all AndroidX / Google libraries from the list.\n\n\nThanks to this StackOverflow answer for the tip.\n"
    } ,
  
    {
      "tags"     : "AppBundles, Jetpack, Kotlin, Modules, Testing",
      "title"    : "2020's essential Android development techniques",
      "excerpt"  : "Earlier this year, myself and the rest of the ITV Hub Android team visited Droidcon UK. We thoroughly enjoyed ourselves, and on my return I wrote up my top 5 techniques for Android development in 2020.\n",
      "url"      : "/2020s-essential-android-development-techniques/",
      "date"     : "Dec 14, 2019",
      "content"  : "Earlier this year, myself and the rest of the ITV Hub Android team visited Droidcon UK. We thoroughly enjoyed ourselves, and on my return I wrote up my top 5 techniques for Android development in 2020.\n\nThis is over on Candyspace’s blog, it’s for both developers and their non-techy managers!\n\nPS: If you want spoilers, maybe this post’s tags will help…\n"
    } ,
  
    {
      "tags"     : "DataBinding, Layout, ViewBinding",
      "title"    : "Tutorials overview for data binding",
      "excerpt"  : "Somehow I’ve spent a few years developing for Android without coming across data binding in a real project. I’ve seen it mentioned, assumed the basics, but never actually used it. I recently had the opportunity to use some of it’s more advanced capabilities for work, which seemed a good time to try out the most popular data binding tutorials!\n",
      "url"      : "/tutorials-overview-for-data-binding/",
      "date"     : "Jul 30, 2019",
      "content"  : "Somehow I’ve spent a few years developing for Android without coming across data binding in a real project. I’ve seen it mentioned, assumed the basics, but never actually used it. I recently had the opportunity to use some of it’s more advanced capabilities for work, which seemed a good time to try out the most popular data binding tutorials!\n\nMy method of finding tutorials was very simple, I just Googled “data binding android tutorial” and ran through the top 5! I followed all of the tutorials inside one project (available on GitHub), with branches and regular commits for each tutorial. Whilst this post will hopefully help you choose a tutorial, the repository will also give a nice example of the finished product. Tutorials are listed in the order they appeared in my search results.\n\n“Using data binding in Android” – Lars Vogel\n\nAs with all Vogella tutorials, this lengthy article very much prioritises showing over telling. Whilst this is often a good tactic, in this case it results in any reader just blindly copy and pasting code without actually knowing what it does. For example, step 2.1 – 2.5 are an exercise for the reader that tells them nothing except “run this code”. Whilst there is some explanation of (similar) code in step 1, the subtle differences mean this isn’t actually very helpful.\n\nThe end result is a technically competent implementation of data binding, but with little actual knowledge transferred. As seems to be a running theme in Vogella tutorials, I believe the code was created first, then a tutorial written up as an afterthought. There are a few small typos through the article, but the actual code is nicely formatted etc.\n\nOne advantage of this tutorial is it does go slightly beyond the basics, by introducing binding adapters. This nice idea is unfortunately immediately counteracted by the lack of any explanation of what a custom converter is, why you might use one, or what the considerations of use are.\n\nI really wish I could get on better with the tutorial, but just being shown screens of code with little explanation is barely better than a GitHub repo.\n\n“Android working with DataBinding” – Ravi Tamada\n\nAs a contrast to the previous tutorial, AndroidHive’s data binding tutorial explains all code shown. It very clearly explains the concept and reasoning behind data binding, as well as explaining what every block of code does.\n\nUnusually for these tutorials, FAB / button click events were covered in detail. From passing parameters to binding the handler, the common use cases were covered nicely. A nice touch was providing binding adapter instructions for Picasso &amp; Glide, allowing users to apply whatever existing image loading library knowledge they had.\n\nA short but sweet tutorial, it’s definitely worth reading to get to grips with a few core data binding concepts.\n\n“Data Binding for Android Beginners” – Tobiloba Adejumo\n\nThe first distinguishing feature of MindOrks’ tutorial that immediately jumps out is the ability to listen to it. It turns out to just be text-to-speech, it’s a nice idea though!\n\nI like the emphasis on Q&amp;A this article starts with, helping clear up a few concerns before diving into the code. Unfortunately, once this introduction is finished and the bare bones code is explained, the article has ended! Whilst it has some good information inside, the end result is the absolute bare minimum data binding implementation possible.\n\nIn the article’s defence it does start with “This is the first article in this series”. But, with no apparent link to the second article even 6 months later, it’s hard to see why it ended up so highly ranked on Google, as it’s not a good resource for beginners.\n\n“Android Data Binding codelab” – Google\n\nAs the official data binding resource from Google themselves, I had high hopes for their codelab tutorial. High hopes that were lived up to by the extremely high level of quality throughout.\n\nThe inclusion of screenshots and helpful tips alongside the code really helps enhance understanding. Additionally, as the code files aren’t being shown in their entirety repeatedly, actually implementing the codelab requires reading and understanding the instructions.\n\nEach step also contains links to external resources, allowing readers to dive deeper into specific concepts if they are interested / need more information. All of the most used elements of view binding are covered excellently, from binding adapters to live data. Each only explains the concepts as much as is necessary, supplemented by external links.\n\nThe GitHub repo also makes the unusual decision to provide duplicates of the files worked upon, one for each stage of the tutorial. This allows the developer to easily check what their files should look like in case there is any confusion.\n\nHaving the tutorial exclusively in Kotlin is excellent for those of us who mostly work in it, but it would have been nice if there was a Java version too, just like the official Android developer documentation. Perhaps my favourite part of this tutorial is the links to additional samples and further documentation at the very end, encouraging the developer to continue learning.\n\nFrom the codelabs’ clean interface to the engaging writing, this tutorial is by far the highest quality covered in this post. I’d absolutely recommend running through it, even if just to look at the useful resources linked.\n\n“Data Binding in Android” by Morris\n\nThis tutorial by AndroidWave made the decision to produce a fully designed prototype to databind, instead of the usual proof of concept style. This has the significant disadvantage of the first block of code being 150 lines of XML. Almost all of it completely irrelevant to databinding (and containing typos).\n\nIt also has dependencies on drawables, colours, and even custom fonts that need to be implemented, in the first file alone! This same giant block of XML is shown multiple times in the article, with the differences not made clear.\n\nThe quality of the writing is unfortunately relatively low too, with a few sentences requiring a few reads to be understood. As a counterpoint to this though, the end result really is nicely designed!\n"
    } ,
  
    {
      "tags"     : "adb, Intents, Update",
      "title"    : "How to create (and test) an app update listener",
      "excerpt"  : "Running code when your app updates can be a useful marketing tool, and a reliable way of enabling new functionality only when the user updates.\n",
      "url"      : "/how-to-create-and-test-an-app-update-listener/",
      "date"     : "Jun 10, 2019",
      "content"  : "Running code when your app updates can be a useful marketing tool, and a reliable way of enabling new functionality only when the user updates.\n\nFor example, your app may send a message to your server when it updates, so your server knows it can now return more types of content. Similarly, you may want to send a notification to the user (from the app) when it updates, informing them of new content.\n\nWhilst there’s plenty of existing documentation on registering an update listener, much of it is outdated, unsafe, or doesn’t include any information on how to test your implementation. This article will hopefully address these shortcomings, and is also available as a repository and a Gist.\n\nThe approach is very simple; we’re just registering an app update listener in the manifest, and then displaying a toast message inside this listener.\n\nRegistering receiver\n\nThe MY_PACKAGE_REPLACED intent action is only fired when your app is updated. It is only available on APIs 12+ (which should be fine for almost all apps), and replaces the existing PACKAGE_REPLACED. The drawback of the previous technique is it would often be called when any app updates, causing your app to be woken up extremely frequently.\n\nThis receiver (.AppUpgradeReceiver in this case) is registered in your AndroidManifest.xml, within the application tag:\n\n&lt;receiver android:name=\".AppUpgradeReceiver\"&gt;\n    &lt;intent-filter&gt;\n        &lt;action android:name=\"android.intent.action.MY_PACKAGE_REPLACED\" /&gt;\n    &lt;/intent-filter&gt;\n&lt;/receiver&gt;\n\n\nHandling update intent\n\nNow we need to create the AppUpgradeReceiver receiver we just defined. This class extends BroadcastReceiver, which has an onReceive that needs overriding:\n\nclass AppUpgradeReceiver : BroadcastReceiver() {\n\n    @SuppressLint(\"UnsafeProtectedBroadcastReceiver\")\n    override fun onReceive(context: Context?, intent: Intent?) {\n        if (context == null) {\n            return\n        }\n        Toast.makeText(context, \"Updated to version #${BuildConfig.VERSION_CODE}!\", Toast.LENGTH_LONG).show()\n    }\n\n}\n\n\nNote that lint complains that we’re not filtering the incoming intent (to make sure it’s for our package), but this is not needed as we are using the MY_PACKAGE_REPLACED intent. The SuppressLint annotation should only be used when you are intentionally disagreeing with lint’s analysis, as in this situation!\n\nAnd that’s it! Your listener is registered and will show a Toast message of the new version code whenever your app updates.\n\nUpdate (2022-10-06): A helpful commenter (see bottom of post) mentioned that instead of suppressing the lint warning, you can use replace the check with if (context == null || intent?.action != \"android.intent.action.MY_PACKAGE_REPLACED\") {. This is likely a better solution!\n\nTesting\n\nTesting this functionality initially seems intimidating, as uploading a new version to the Play Store every time would be very time consuming; luckily, we can update apps yourselves!\n\nPreviously, testing just required running the new version of your app from Android Studio. Now however, the MY_PACKAGE_REPLACED intent can only be sent by the OS, so is not triggered during normal development.\n\nThe solution is to actually install the app manually:\n\n\n  Increasing the versionCode in your app-level build.gradle (so it counts as an update).\n  Clicking Build -&gt; Build Bundle(s) / APK(s) -&gt; Build APK(s), and selecting a debug APK.\n  Entering the following command into the Terminal tab at the bottom of Android Studio:\n\n\nadb install -r &lt;path to your apk&gt;\n\n\nFor example, the command on a Windows machine to update this tutorial’s app may look like:\n\nadb install -r C:\\\\Repositories\\\\updatelistener\\\\app\\\\build\\\\outputs\\\\apk\\\\debug\\\\app-debug.apk\n\n\nYou should see “Success” underneath your command in the terminal.\n\n\n\nThe app is then updated like normal, and your listener called. In the sample repo, an update will cause the new version code to be displayed in a Toast.\n"
    } ,
  
    {
      "tags"     : "Flair, Reddit",
      "title"    : "How to create HD image flairs, with accompanying text, on your subreddit",
      "excerpt"  : "Over on /r/AndroidDev, we’re shortly going to be hosting AMAs from a few prominent devs. In preparation for this, I wanted to revisit Reddit’s user flair system, so users can have their employer’s icon. Whilst I’ve assigned plenty of flairs over on /r/Android, I’ve never actually created one from scratch. The end result of this tutorial will be the ability to easily give your subreddit’s users custom image flairs, whilst allowing them to add their own text.\n",
      "url"      : "/how-to-create-hd-image-flairs-with-accompanying-text-on-your-subreddit/",
      "date"     : "Jun 7, 2019",
      "content"  : "Over on /r/AndroidDev, we’re shortly going to be hosting AMAs from a few prominent devs. In preparation for this, I wanted to revisit Reddit’s user flair system, so users can have their employer’s icon. Whilst I’ve assigned plenty of flairs over on /r/Android, I’ve never actually created one from scratch. The end result of this tutorial will be the ability to easily give your subreddit’s users custom image flairs, whilst allowing them to add their own text.\n\nNote that most of this post is to do with getting flairs to work on the old reddit design. Getting them working on the new design is much simpler, please skip to that section!\n\nPreparing your icons\n\nFirst, you need to find the images you want to use for flairs. These should be square, and at least 16×16 pixels, although 64×64 will look much better.\n\nYou can find your images from various places, depending on what you’re using flair for. I had to resize a few icons in Photoshop, as a few couldn’t be found in the necessary 64×64.\n\nFor the /r/AndroidDev images, I looked on the company’s branding site, their LinkedIn profile pictures, and sometimes the start of their site’s source code (as it contained a 64×64 favicon). Once I had all my images ready, I moved on to creating a sprite sheet…\n\n\n\nOn Reddit pre-redesign (old reddit)\n\nCreating a sprite sheet\n\nYou now need to make a single image that contains all of your flair images, stacked vertically. You can either do this yourself, or use an online tool like SpriteGen. If using SpriteGen, follow these steps:\n\n\n  Press “Clear” to remove the default images.\n  Press “Open” and add all of your sprites.\n  Under Settings, change your Layout to “Vertical” and your Padding to “0px”.\n  Your images should now look like the image below.\n  Click “Downloads” and click “Spritesheet”. Note that CSS is generated by this tool, but it’s not useful for our purposes!\n  Rename this file to flair-spritesheet.png or similar, as many themes already have a spritesheet.png.\n\n\n\n\nCreating your CSS\n\nYou now need to make the actual changes to your subreddit! We’ll upload our spritesheet, then set up some CSS to give styles to the flair classes.\n\nFirst, head to your subreddit’s stylesheet (“edit stylesheet” on sidebar or https://www.reddit.com/r/yoursubredditname/about/stylesheet/). Then, on the image selector, choose your flair-spritesheet.png, make sure the “new image name” is flair-spritesheet, and press “Upload”.\n\nAdd the following to the very bottom of the (possibly empty) CSS code box:\n\n.flair:before{\n    content:\"\";\n    height:16px; /* size of displayed image */\n    margin-top:-2px;\n    background-repeat:no-repeat;\n    background-image:url(%%flair-spritesheet%%); /* name of the flair spritesheet uploaded */\n    background-size:auto 64px; /* 64px = total height of image */\n    display:inline-block;\n    vertical-align:middle\n}\n\n.flair-android:before{width:16px;background-position: 0 -0px}\n.flair-discord:before{width:16px;background-position: 0 -16px}\n.flair-google:before{width:16px;background-position: 0 -32px}\n.flair-nerdery:before{width:16px;background-position: 0 -48px}\n\n\nEach flair we’re adding is a new CSS class, with a very simple piece of code. This code sets the image flair’s width, and how much of an offset on the spritesheet to use to find the image. Under the .flair:before‘s class, the background-size value must be changed if you are using an image size other than 64×64.\n\nWe now have flair classes of android, discord, google, and nerdery set up!\n\nAssigning the flair\n\nTo actually give users this flair, head to the “edit flair” option in the sidebar (or https://new.reddit.com/r/androiddev/about/flair). Under the “grant flair” tab, enter the user you wish to give a flair, and press “Go”.\n\nYou can now choose the text that appears next to their name, as well as the image flair. For example, I want the Discord icon next to my name, so I set discord as the CSS class (derived from the flair-discord CSS class defined earlier).\n\nPress “Save”, and you’ll see the new flair:\n\n\n\nAnd here’s how it looks next to my name. Perfect!\n\n\n\nAdding new flairs\n\nTo add new flairs, just:\n\n\n  Add your new 64×64 image to the bottom of the flair-spritesheet.png.\n  Reupload it, overwriting the existing one.\n  Add a new row to the CSS, with the final number changed to 16px lower than the last row.\n  Change background-size:auto 64px to be 16 x the number of icons (so 16 higher than the previous value).\n  Save the CSS.\n\n\nFor example, if I was going to add a new flair after .flair-nerdery:before{width:16px;background-position: 0 -48px}, it would be .flair-newcompany:before{width:16px;background-position: 0 -64px}, and the auto 64px bit would change to auto 80px.\n\nOn Reddit post-redesign (new reddit)\n\nUpload emoji\n\nOn the “Emojis” page (Mod Tools -&gt; Emojis, or https://new.reddit.com/r/yoursubredditname/about/emojis), add a new emoji via the “Add Emoji” button in the top right. This should be the square image prepared earlier in the post, and images can be uploaded in bulk. Make sure the “Mod only” slider is enabled.\n\nCreate user flair template\n\nOn the “User flair” page (Mod Tools -&gt; User flair, or https://new.reddit.com/r/androiddev/about/flair), click the “Add flair” button in the top right.\n\nMake sure you tick “Mod only” first, otherwise mod-only emojis won’t appear. Then set your flair text to “[emoji] Your text” (see example below), and your CSS class from earlier. Emojis can be added by clicking the smiley face icon.\n\n\n\nAssign the flair\n\nFinally, on the “Grant user flair” page (Mod Tools -&gt; Grant user flair, or https://new.reddit.com/r/androiddev/about/flair), search for the user you want to give flair, and set their Flair Template and CSS Class. The newly created flair template should be used, and will end up looking like this:\n\n\n\nFinal thoughts\n\nI’d like to mention a frequently referenced user flair tutorial from 2015. I used this for my first attempt, but discovered that it could only handle 16×16 images, which looked pretty bad in almost all cases. Additionally, if you are going to use other sizes than 16px for the displayed image and 64px for the source images, you just need to replace every instance of the value. You can have much larger displayed flairs, but they’ll start messing up the page’s layout pretty quickly!\n\nThe first version of this post didn’t mention the redesign, as I didn’t believe mod-only image flairs were possible. Special thanks to Geo☆1088#2272 on the Reddit Mod discord for helping me figure it out. The redesign definitely makes it a lot easier, although it’s unfortunate that effort needs to be duplicated to work on both systems.\n"
    } ,
  
    {
      "tags"     : "API, Retrofit",
      "title"    : "Tutorials overview for Retrofit",
      "excerpt"  : "Whilst I’ve used Retrofit before, I’d always just used the very basics and not thought much about it. Hey, it’s just the API interface, who cares right? I decided to check out a few implementations of the basics, making a repo along the way. This GitHub repo is available here, and contains completed versions of most of the tutorials listed here.\n",
      "url"      : "/tutorials-overview-for-retrofit/",
      "date"     : "Jun 5, 2019",
      "content"  : "Whilst I’ve used Retrofit before, I’d always just used the very basics and not thought much about it. Hey, it’s just the API interface, who cares right? I decided to check out a few implementations of the basics, making a repo along the way. This GitHub repo is available here, and contains completed versions of most of the tutorials listed here.\n\nThis post will very briefly cover the few tutorials used, although not all were completed fully for various reasons.\n\n“Retrofit – A simple Android tutorial” – Prakash Pun\n\nThis tutorial starts off strong, providing prominent links to the example repo and library. Each step is clearly defined, as well as why the code is needed. Luckily, Prakash also avoids falling into the mistake of pages upon pages of boilerplate code, and keeps it simple.\n\nWhilst there are minor typos (progressDoalog springs to mind), the overall code works out of the box, and produces an impressive end result.\n\nThe tutorial perfectly shows the core Retrofit concepts, albeit perhaps in not quite enough detail, but it’s an absolutely solid starting point. Another improvement would be suggestions for related resources at the end, for those curious readers who want to learn more.\n\n“Using Retrofit 2.x as REST client” – Vogella\n\nThis tutorial contains a few examples of uses, and dives quite deep into the entire app creation process.\n\nI found this tutorial fairly disappointing. Whilst it contained a lot of useful information, there were quite a few massive mistakes (e.g. sections 3 &amp; 6 contain exactly the same text and code, presumably a poor copy and paste job).\n\nThe dive into XML processing was a nice change from the GSON parsing all tutorials use, but the code was rarely explained sufficiently. Instead the entire file was displayed, with little surrounding information, jumping between many files without much discussion of why.\n\nThe final issue was the same (large) files being displayed in full repeatedly, with minor changes, requiring close inspection to find the changes. Whilst the end result is multiple useful Retrofit implementations, the emphasis on non-Retrofit boilerplate code reduces the usefulness. Unfortunately I gave up on the tutorial after the 8th section, as the mistakes got somewhat overwhelming!\n\n“Retrofit Android Example Tutorial” – Anupam Chugh\n\nThis tutorial uses Reqres to handle fake data generation, making the example seem more realistic. Whilst the tutorial (as seems common) suffers from a few typos, and the end code is rather spaghetti-like, it utilises an impressive array of Retrofit features. In a single tutorial, it manages to cover all of the basics, as well as exploring OkHTTP’s interceptors to change the logging configuration.\n\nOne downside of the tutorial is the code blocks not being sufficiently explained, and instead just appearing. As an example, the final step adds 70-80 lines to MainActivity.java, with just a 1 sentence explanation of the overall effect.\n\nDespite the drawbacks, this tutorial ends up with a pretty powerful Activity, capable of GETting and POSTing multiple resource types. As always, a nice improvement would be further reading suggestions.\n"
    } ,
  
    {
      "tags"     : "Dagger2, DependencyInjection, DI, Tutorial",
      "title"    : "Tutorials overview for Dagger 2",
      "excerpt"  : "Whilst I’ve used the dependency injector Dagger 2 a few times before, my knowledge was very much gained “in the field”, i.e. from seeing it in the wild. I recently decided to learn how to use it properly, so worked through a few of the more popular tutorials inside a repo. This GitHub repo is available here, and contains completed versions of all of the tutorials listed here.\n",
      "url"      : "/tutorials-overview-for-dagger-2/",
      "date"     : "Jun 4, 2019",
      "content"  : "Whilst I’ve used the dependency injector Dagger 2 a few times before, my knowledge was very much gained “in the field”, i.e. from seeing it in the wild. I recently decided to learn how to use it properly, so worked through a few of the more popular tutorials inside a repo. This GitHub repo is available here, and contains completed versions of all of the tutorials listed here.\n\nIn this post I’ll briefly cover the 5 tutorial series used. They’re all very high quality, and I’m extremely grateful to the authors for helping improve my understanding!\n\nPS: The /r/AndroidDev Discord server has a #dependency-injection channel if you need any Dagger 2 help.\n\n“Dagger 2 for Dummies in Kotlin” – Elye\n\nThis series by Elye was my personal favourite mentioned in this post. It ramped the difficulty up very gently, keeping all implementations as simple as possible to avoid confusion. The writing style is very informal, the memes / typos of which can be a little distracting, but the clear content outweighs this.\n\nAll of the posts contain plenty of diagrams, which really aid understanding of the more abstract concepts of Dagger. Intuitive names (e.g. “MagicBox”) are used, along with notes on the more common naming standards.\n\nIt comes in 6 parts (Intro, Provides &amp; Module, Qualifier, Testing, Scope, Subcomponent), each of which have a repo at the end.\n\n“An Absolute Beginner’s Tutorial on … Dependency Injection” – Rahul Rajat Singh\n\nThis tutorial from 2013 is not Android, or even Java specific. It instead introduces the concepts of dependency inversion, inversion of control, and dependency injection, essential to Dagger. Whilst it is written in C#, the concepts are all simple enough that rewriting them in Kotlin was not a particularly tricky barrier. Admittedly, without having prior C# knowledge this would have been more challenging, but the extremely high quality of the writing convinced me to work through it.\n\nAll of the concepts are worked through completely, with the surrounding logic / concepts described in a very straightforward manner. The example used throughout is to do with logging system messages.\n\nThe post has been rewritten into Kotlin within my implementation repo, which may be helpful when following along.\n\n“Introduction to Dagger 2” – Donato Rimenti\n\nThis single-page tutorial is very short and simple, and effectively shows all of the core Dagger concepts. However, this conciseness and text-only style risks alienating some devs who aren’t already familiar with the concepts within.\n\nThe post is written in Java, and uses a intuitive “Car with an Engine and Brand” example.\n\n“Dagger 2 Tutorial: Dependency Injection Made Easy” – Jose Manuel Garcia Maestre\n\nThis tutorial is another single-page one, that provides the minimum knowledge needed to get started with Dagger. Unfortunately this tutorial doesn’t dive very deep, and uses an unnecessarily confusing example (injecting blood types into a body). Still, it provides the reader with the essentials, and would be useful as a refresher article.\n\n“How-to Dagger 2 with Android” – John Tucker\n\nThis 2 part tutorial (part 1, part 2) suffers a little bit from jumping around many files, risking the reader losing track of what the core concepts actually are, and getting caught up in boilerplate code. The posts are very code heavy, which can be beneficial for some readers, but personally I would have preferred more explanation along the way.\n"
    } ,
  
    {
      "tags"     : "9patch, Background, Drawable",
      "title"    : "How to use 9-patch images for resizable backgrounds in Android",
      "excerpt"  : "In Android, almost all views can have a background colour or image set. Whilst a colour can be any size / shape, as can a vector drawable, a bitmap drawable cannot. For example, trying to make a 100px wide &amp; 100px tall image 500px wide and 50px tall would result in a blurry, and horribly distorted background.\n",
      "url"      : "/how-to-use-9-patch-images-for-resizable-backgrounds-in-android/",
      "date"     : "Jun 3, 2019",
      "content"  : "In Android, almost all views can have a background colour or image set. Whilst a colour can be any size / shape, as can a vector drawable, a bitmap drawable cannot. For example, trying to make a 100px wide &amp; 100px tall image 500px wide and 50px tall would result in a blurry, and horribly distorted background.\n\nMy early apps suffered from this often (e.g. Pixel Blacksmith), but there is a solution! So long as the image you’re using has consistent (stretchable) bars on the top and side, 9 patch images may be the answer.\n\n9 patch images are a type of PNG (identified by their .9.png file extension) that define which parts of the image can be “stretched” to fill the required space. In this example, the corners of a background image will be marked non-stretchable, whilst the top and bottom sections will be marked as stretchable. This will result in the image being able to fit any ImageView or background.\n\nNormal PNG\n\n\n\nJust setting the PNG as the background technically works, as the image resizes, but the flaws are immediately obvious if you click the thumbnail on the left to view the full image.\n\nThe corners are impressively both pixellated AND blurry, as Android tries to scale the small image to a much larger area. This effect is most obvious on “Wide”, but even “Small” shows some hints of it.\n\n9-Patch PNG\n\n\n\nOnce the image has been converted to a 9-patch, it handles all of the earlier situations perfectly. There is no blurriness or pixellation, and the “Small” square is handled just as gracefully as the larger ones.\n\nThis tutorial will walk you through the 9-patch editor, and provide a few tips for converting your own PNGs.\n\nIntroduction to 9-patch PNG editor\n\nAndroid Studio’s built in 9-patch editor can be intimidating at first glance, but it’s actually very, very simple. All it does it allow you to set stretchable areas by modifying the black / transparent pixels around the edge of your image. It will also help warn you of potential issues with your 9-patch.\n\nTo create your first 9-patch:\n\n\n  Inside Android Studio, right click your PNG inside res/drawable.\n  Select “Create 9-Patch file…”.\n  Select where the file should be placed (usually the same res/drawable folder).\n  This will open up the 9 patch editor, described below:\n\n\n\n\nThe 9-patch editor consists of:\n\n\n  The 9-patch’s name.\n  The editing window, where the scalable areas can be defined.\n  A transparent bordered area, meaning this area cannot be stretched.\n  A black bordered area, meaning this area can be stretched.\n  When hovering over a side of the image, a “resize” icon lets you modify the stretchable / non-stretchable area.\n  The preview pane, where the 9-patch’s appearance can be seen.\n  Adjusting zoom in the editing window.\n  Adjusting zoom in the preview window.\n  Additional options, consisting of:\n    \n      Show lock: This highlights (in the preview pane, when moused over) which parts of the image can be changed for the 9 patch (a border of 1px).\n      Show content: This highlights (in the preview pane) which parts of the drawable can contain content if it is used as a background. For example, on a TextView it will highlight where text can go. This is defined as the largest possible stretchable space (black outlines in diagram above).\n      Show patches: This highlights (in the editing pane) the stretchable areas (green) and content area (purple).\n      Show bad patches: When “Show patches” is ticked, this highlights (in the editing pane) whether any of your stretchable areas are “bad”. An area is “bad” if the pixels vary in colour (except if they’re in the opposite direction to the stretch). Your 9-patch image will still work, but is likely to not look perfect. This StackOverflow answer contains a visual example.\n    \n  \n\n\nNote: The top and left bars define which areas are stretchable, but the bottom and right actually define which areas should contain content. These are often the same, but you may want them to be slightly different (e.g. to apply a bit of extra padding around the content).\n\nTips for converting PNGs to 9-patch\n\nIn most cases, your 9-patch will end up perfectly symmetrical (vertically &amp; horizontally), with black bars on all 4 edges and transparent corners. This will allow the edges to stretch, but not the corners. For example, here is how the earlier example looks in the editor:\n\n\n\nMake sure to check your image with “Show bad patches”, to make sure no almost unnoticeable stretching issues will occur.\n\nAdditionally, don’t forget to delete the original .png file, otherwise the build will fail due to duplicated resources.\n\nFinally, if you’d like to look at the original image and play with the final 9-patch image, the repo used for this post is available on GitHub.\n"
    } ,
  
    {
      "tags"     : "Command, Discord, Dyno",
      "title"    : "Using Dyno to create a Discord command that displays a message and DMs a specified user",
      "excerpt"  : "Dyno is an extremely powerful bot for Discord, with a staggering set of features, split into modules. One of the easiest to use is the “Custom Command” module, allowing actions to be taken in response to messages in chat. Setting up Dyno to a server you have “Manage server” permissions on is very straightforward, just click “Add to server” on Dyno.gg, then follow the instructions.\n",
      "url"      : "/using-dyno-to-create-a-discord-command-that-displays-a-message-and-dms-a-specified-user/",
      "date"     : "May 20, 2019",
      "content"  : "Dyno is an extremely powerful bot for Discord, with a staggering set of features, split into modules. One of the easiest to use is the “Custom Command” module, allowing actions to be taken in response to messages in chat. Setting up Dyno to a server you have “Manage server” permissions on is very straightforward, just click “Add to server” on Dyno.gg, then follow the instructions.\n\nOn the Android Dev and Flutter Dev servers, there are a few commands currently in use. Most of them are simple autoresponses (displaying a message when a command like ?screenshot is entered), but the longer autoresponses take up far too much room in chat. To get around this, I implemented a solution that DMs the response to a specified user, and displays a confirmation message in the original channel.\n\nCommand code\n\nHere’s the code used on the Android Dev discord to let users send each other information on Kotlin, using ?kotlin @Username#123:\n\n{delete}{!announce {channel} Sending Kotlin resources to $1 on behalf of {user.mention}!} \n{dm:$1} \nLooking to get started with Kotlin development? \nHere's a Udacity course: &lt;https://www.udacity.com/course/developing-android-apps-with-kotlin--ud9012&gt; \nAnd a useful wiki if you already know Java: &lt;https://github.com/Zhuinden/guide-to-kotlin/wiki&gt;\n\n\nThe command can look a little complicated, so here’s what each part does:\n\n\n  The curly braces ({ &amp; }) wrap each part of the command.\n  delete deletes the command (?kotlin) used to summon the bot.\n  !announce uses Dyno’s announce command to display the “X has sent resources to Y” message in chat.\n    \n      channel tells Dyno to output the message in the channel where the command was sent.\n      $1 tells Dyno to use the first parameter sent to it, in this case the target user (X).\n      user.mention references the user who sent the initial command (Y).\n    \n  \n  dm:$1 sends a private message (DM) to $1, which is described above.\n  Finally, &lt; and &gt; are used around links to prevent them displaying large embeds.\n\n\nHere’s what displays in the channel:\n\n\n\nAnd here’s what the user receives in their inbox:\n\n\n\nThis approach unfortunately doesn’t work if a user has blocked Dyno. However, this is relatively unusual it’s generally not worth considering as a downside.\n\nOverall the approach is simple to adapt and extend, and adds powerful functionality to any server. If your servers uses commands like this, make sure it also has a #botspam channel for people to try out the commands!\n\nFinally, here’s how the command will look on your Dyno Custom Commands list:\n\n\n"
    } ,
  
    {
      "tags"     : "Preview, TaskSwitcher",
      "title"    : "How to disable your app's preview image in Android's task / app switcher",
      "excerpt"  : "The easiest way to disable your app’s preview when your app is shown in task switcher is FLAG_SECURE.\n",
      "url"      : "/how-to-disable-your-apps-preview-image-in-androids-task-app-switcher/",
      "date"     : "May 13, 2019",
      "content"  : "The easiest way to disable your app’s preview when your app is shown in task switcher is FLAG_SECURE.\n\nWhen this is enabled, your app won’t display any previews, and instead shows a blank screen for most devices.\n\nThis can be done by creating a base Activity class that all activities extend, containing this in the onCreate:\n\nprotected void onCreate(@Nullable Bundle savedInstanceState) {\n    getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);\n    super.onCreate(savedInstanceState);\n}\n\n\nAlternatively, you can selectively enable it on pause / resume (although the first approach is better):\n\noverride fun onPause() {\n    super.onPause()\n    getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)\n}\n\noverride fun onResume() {\n    super.onResume()\n    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE)\n}\n\n\nOriginally from my (ultimately unhelpful) StackOverflow answer.\n"
    } ,
  
    {
      "tags"     : "Icon, Kotlin, Manifest",
      "title"    : "How to programmatically change your Android app icon and name",
      "excerpt"  : "In Android, your app’s icon is a crucial part of your project. It’s what grabs the user’s attention first, identifies your app amongst the sea of competitors, and is the most important piece of visual branding. However, usually this icon is defined in your manifest, then never changes except through update.\n",
      "url"      : "/programmatically-changing-app-icon/",
      "date"     : "Apr 29, 2019",
      "content"  : "In Android, your app’s icon is a crucial part of your project. It’s what grabs the user’s attention first, identifies your app amongst the sea of competitors, and is the most important piece of visual branding. However, usually this icon is defined in your manifest, then never changes except through update.\n\nRecently, out of curiosity, I discovered it was possible to change the app icon / name whenever you want, without an update. Luckily, it’s pretty straightforward! Whilst this article is a detailed explanation of the solution, it is also available as a Gist, and an example project.\n\nApproach\n\nThe android.intent.action.MAIN action (which usually exists on your default activity) tells Android which activity should be used to start your app. However, we can define multiple aliases for our single activity, with the end result of multiple configurations of icon + title for our app.\n\nAll of our activity aliases will define themselves as the starting point to the app, so we’ll need to disable all the ones not currently in use. This will result in the OS only showing the remaining activated alias on the app launcher. Note that this can take a few seconds to take effect, and almost certainly has strange side effects!\n\nRegistering aliases in manifest\n\nFirst, remove the MAIN action (&lt;action android:name=\"android.intent.action.MAIN\" /&gt;) from your app’s launcher activity (by default MainActivity). This is so our aliases can use it instead. Your activity should end up something like this:\n\n&lt;activity android:name=\".MainActivity\"&gt;\n    &lt;intent-filter&gt;\n        &lt;category android:name=\"android.intent.category.LAUNCHER\"/&gt;\n    &lt;/intent-filter&gt;\n&lt;/activity&gt;\n\n\nNext, add an &lt;activity-alias&gt; for every different icon / name you want your app to use. There are a few required fields:\n\n\n  label for the app’s display name\n  icon for the app’s icon. This can be a drawable or mipmap, with mipmap recommended.\n  name can be any valid string (no special characters, spaces, etc), and is used to reference this alias later on. In this example I’ve used the colour of the icon.\n  targetActivity must be your existing launcher activity.\n  enabled must be set to true for at least one of your activity-alias. Otherwise, your app will not be able to launch.\n\n\n&lt;activity-alias\n        android:label=\"Red app\"\n        android:icon=\"@mipmap/icon_red\"\n        android:name=\".RED\"\n        android:enabled=\"true\"\n        android:targetActivity=\".MainActivity\"&gt;\n    &lt;intent-filter&gt;\n        &lt;action android:name=\"android.intent.action.MAIN\" /&gt;\n        &lt;category android:name=\"android.intent.category.LAUNCHER\" /&gt;\n    &lt;/intent-filter&gt;\n&lt;/activity-alias&gt;\n\n\nIcon switching\n\nTo enable one of our aliases, we also need to disable all others. The core piece of code used for this is below, with PackageManager.COMPONENT_ENABLED_STATE_ENABLED changed to ...STATE_DISABLED for the unwanted aliases:\n\ngetPackageManager().setComponentEnabledSetting(\n    new ComponentName(BuildConfig.APPLICATION_ID, \"com.example.package.RED\"), \n    PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP\n);\n\n\nThe BuildConfig.APPLICATION_ID is used to tell the package manager which package you want to modify a component of. \"com.example.package.RED\" should be your package name, then the activity-alias‘ name defined in the previous step. If you’re using Kotlin, the easiest way to set this is using inline string formatting, e.g:\n\n\"${BuildConfig.APPLICATION_ID}.$aliasName\"\n\n\nFurther usage\n\nA good way to ensure all other activity aliases are disabled when one is enabled is to use a helper function along with an enum. This enum should contain every possible activity alias. Then, loop over this enum and set all values to the necessary state:\n\nenum class ICON_COLOUR { RED, GREEN, BLUE }\n\nprivate fun setIcon(targetColour: ICON_COLOUR) {\n    for (value in ICON_COLOUR.values()) {\n        val action = if (value == targetColour) {\n            PackageManager.COMPONENT_ENABLED_STATE_ENABLED\n        } else {\n            PackageManager.COMPONENT_ENABLED_STATE_DISABLED\n        }\n        packageManager.setComponentEnabledSetting(\n            ComponentName(BuildConfig.APPLICATION_ID, \"${BuildConfig.APPLICATION_ID}.${value.name}\"),\n            action, PackageManager.DONT_KILL_APP\n        )\n    }\n}\n\n\nApp icons can then be changed with just setIcon(ICON_COLOUR.RED). Easy!\n\nNotes\n\nI noticed a few quirks during my experimenting with this, and I’d be hesitant to use it in a production app without extensive testing. A couple of notable issues:\n\n\n  If you programmatically change your alias, it can take a few seconds for the launcher to update.\n  Related to the previous issue, if you try to open the app via the icon during these few seconds, there will be a mismatch between the launcher shortcut and the manifest. The OS will then be unable to open your app, and display an App not found toast.\n  If you are trying to deploy an app that has had it’s alias changed since install, Android Studio will fail to launch it. It will need to be uninstalled or reset back to the default.\n  The original title and icon will show in many places throughout the OS. For example:\n    \n      Task switcher\n      Applications list\n    \n  \n  Non-default launchers may not display this changed icon.\n\n\nSpecial thanks to this StackOverflow answer by P-A for the core code. Note that the accepted answer on that question will not work from Marshmallow onwards, as it requires dangerous permissions (add / remove shortcuts), and doesn’t perform as reliably anyway. As such, the answer linked to is the one used for this post.\n\nConclusion\n\nIn conclusion, yes it is possible to change the app icon. However, I wouldn’t rely on this at all, and would personally stick to just changing it with an app update in almost all cases.\n\nThat being said, there’s definitely a lot of potential to this very underused technique. For example, a game where the app icon changes colour whilst it’s the player’s turn, or during a timed event. In this context, it’s like a very limited notification, that the user can’t even turn off! I’d be interested to see which games / apps use this feature in the wild, and if they’ve experienced any side effects.\n"
    } ,
  
    {
      "tags"     : "Androidx, Kotlin, Navigation",
      "title"    : "Resolving crash \"IllegalArgumentException x is unknown to this NavController\"",
      "excerpt"  : "Google’s AndroidX navigation libraries are undoubtedly extremely useful, however they have a few quirks. For example, the following stack trace recently started showing up in my Crashlytics crash logs:\n",
      "url"      : "/resolving-crash-illegalargumentexception-x-is-unknown-to-this-navcontroller/",
      "date"     : "Apr 25, 2019",
      "content"  : "Google’s AndroidX navigation libraries are undoubtedly extremely useful, however they have a few quirks. For example, the following stack trace recently started showing up in my Crashlytics crash logs:\n\nFatal Exception: java.lang.IllegalArgumentException\nnavigation destination com.example.myapp:id/myActionId is unknown to this NavController\n\n\nI couldn’t figure out how it was happening, as all other logging seemed normal. It was happening very rarely on a wide variety of devices, and the root cause was a little surprising. When navigating to another fragment using myNavController.navigate(R.id.myFragment, bundle), a crash happens if two navigation events are triggered close together. This often happens if you have a list of links, and the user (accidentally) presses on two at once.\n\nThis is caused by the navigation controller changing the user’s location in the app to the destination immediately. This means the second navigation click can’t find the navigation action, as the action is not available on the destination fragment. For example, if a fragment has nav graph actions to go to SubFragmentA and SubFragmentB, pressing both links at once will result in:\n\n\n  First, NavController receives SubFragmentA navigation event whilst on Fragment1.\n  The NavController looks up navigation event on Fragment1, and finds it.\n  Then the NavController recognizes that the new location is SubFragmentA and starts playing any transitions.\n  Next, NavController receives SubFragmentB navigation event whilst on SubFragmentA.\n  Then the NavController tries to look up navigation event on SubFragmentA, and fails to find it.\n  Crash!\n\n\nThere are 2 easy solutions to this. The first is preferred, but not always possible.\n\nChecking current location\n\nThe first solution is to check the current location is correct before acting on an action. This will stop the above process before #4. The downside of this is needing to always know the layout of your app, and being unable to reuse navigation actions easily from other fragments. However, for a simple app / use case this will instantly resolve the issue:\n\nif (it.findNavController().currentDestination?.id == R.id.fragment_dashboard) {\n    it.findNavController().navigate(R.id.fragment_detail)\n}\n\n\nNote that R.id.fragment_dashboard is the nav graph ID of the current fragment, and R.id.fragment_detail is the nav graph ID of the target fragment.\n\nCatching exception\n\nThe second solution is a lot less attractive, and involves simply catching the thrown exception. This lets the first navigation continue as expected, and ignores the second navigation.\n\ntry { \n    it.findNavController().navigate(R.id.toDetails)\n} catch (e: IllegalArgumentException) {\n    // User tried tapping 2 links at once!\n    Timber.e(\"Can't open 2 links at once!\")\n}\n\n"
    } ,
  
    {
      "tags"     : "Kotlin, power saving, Sony",
      "title"    : "How to check if a Sony Android device has \"Stamina mode\" enabled",
      "excerpt"  : "Whilst detecting power saving mode (at least on Lollipop+) is very easy, some manufacturers implement their own battery saving systems. One of the least standards-conforming of these is Sony’s Stamina Mode. Luckily this is easily detected, albeit in an unofficial way.\n",
      "url"      : "/how-to-check-if-a-sony-android-device-has-stamina-mode-enabled/",
      "date"     : "Apr 17, 2019",
      "content"  : "Whilst detecting power saving mode (at least on Lollipop+) is very easy, some manufacturers implement their own battery saving systems. One of the least standards-conforming of these is Sony’s Stamina Mode. Luckily this is easily detected, albeit in an unofficial way.\n\nIt’s important to note that this method only detects if the mode is enabled in general, not whether it is currently in use. For example, if a user has the mode set to activate on &lt;15% battery, this method will return true even if the battery is currently 100%. Regardless, since the only official response is “there is no official way” from 5 years ago, this is the best available for now!\n\nFirst, check the device is a Sony device. If it’s not, stamina mode definitely won’t be on!\n\nif (Build.MANUFACTURER.toUpperCase() == \"SONY\") {\n\n\nNext, check if the somc.stamina_mode settings value is set to 1. This is done by using android.provider.Settings, you may need to replace contentResolver with context.getContentResolver():\n\nSettings.Secure.getInt(contentResolver, \"somc.stamina_mode\", 0) == 1\n\n\nFor example, a Kotlin function to display a bar if Sony’s Stamina Mode is on may look like:\n\nprivate fun performSonyPowerSavingCheck() {\n    if (Build.MANUFACTURER.toUpperCase() == \"SONY\") {\n        togglePowerSavingBar(\n            Settings.Secure.getInt(contentResolver, \"somc.stamina_mode\", 0) == 1\n        )\n    }\n}\n\n"
    } ,
  
    {
      "tags"     : "Google Maps, Google Play Services",
      "title"    : "How to fix NoClassDefFoundError \"Failed resolution of: Lorg/apache/http/ProtocolVersion\"",
      "excerpt"  : "I recently updated an older app, and changed the target API from 27 to 28, as recommended. This app is using an older (15.x.x) version of the Google Maps library. Upon trying to actually use Google Maps, I received the following crash:\n",
      "url"      : "/how-to-fix-noclassdeffounderror-failed-resolution-of-lorg-apache-http-protocolversion/",
      "date"     : "Apr 9, 2019",
      "content"  : "I recently updated an older app, and changed the target API from 27 to 28, as recommended. This app is using an older (15.x.x) version of the Google Maps library. Upon trying to actually use Google Maps, I received the following crash:\n\nFatal Exception: java.lang.NoClassDefFoundError\nFailed resolution of: Lorg/apache/http/ProtocolVersion;\n\n\nWith a detailed message of:\nCaused by java.lang.ClassNotFoundException\nDidn't find class \"org.apache.http.ProtocolVersion\" on path: DexPathList[[zip file \"/data/user_de/0/com.google.android.gms/app_chimera/m/0000003d/MapsDynamite.apk\"],nativeLibraryDirectories=[/data/user_de/0/com.google.android.gms/app_chimera/m/0000003d/MapsDynamite.apk!/lib/armeabi-v7a, /data/user_de/0/com.google.android.gms/app_chimera/m/0000003d/MapsDynamite.apk!/lib/armeabi, /system/lib]]\n\n\nNewer Android versions no longer include the library (Apache HTTP) Google Maps and other libraries require, leading to this problem.\n\nThe recommended solution is to either update the Google Maps dependency in the Gradle file to at least 16.1.x (or update whichever library has the issue), but there is another workaround too. Just adding a declaration that you still need the library into your manifest within the &lt;application&gt; tag will resolve it:\n\n&lt;uses-library\n    android:name=\"org.apache.http.legacy\"\n    android:required=\"false\"\n\n\nFurther information about why Google made this change is available here, as is an official recommendation of the manifest approach.\n"
    } ,
  
    {
      "tags"     : "Git, GitHub, gpg",
      "title"    : "Quickly setting up commit verification / signing with GitHub, GitKraken, and GPG",
      "excerpt"  : "Whilst most developers use hosted git repositories on a service like GitHub, many forget that almost none of these commits are verified. If you own a repository, you can “fake” a commit from literally any user if you know their email. If that email matches a GitHub account, their avatar will be displayed next to their name! One famous example is a fake commit by Linus Torvalds.\n",
      "url"      : "/quickly-setting-up-commit-verification-signing-with-github-gitkraken-and-gpg/",
      "date"     : "Mar 20, 2019",
      "content"  : "Whilst most developers use hosted git repositories on a service like GitHub, many forget that almost none of these commits are verified. If you own a repository, you can “fake” a commit from literally any user if you know their email. If that email matches a GitHub account, their avatar will be displayed next to their name! One famous example is a fake commit by Linus Torvalds.\n\nAn effortless way to protect against this is with git verified signatures. This proves that a commit was really from the person. GitKraken introduced this feature a week ago, and it seems to work perfectly. This tutorial will provide a very simple guide to getting verified commits configured.\n\nNote that GitKraken also has a very in-depth guide with lots of extra information.\n\nInstalling GPG\n\nFirst, download Gpg4win (select $0 donation if you do not wish to donate, mac / linux options also available).\n\nNext follow the installer’s steps, deselecting GPGOL (Outlook email signing) and GPGEX (Right-click signing).\n\n\n\nGPG is now installed!\n\nGetting a GPG key\n\nUnder GitKraken’s GPG Preferences (File -&gt; Preferences -&gt; GPG Preferences), browse for your newly installed GPG program. By default, this is at C:\\Program Files (x86)\\GnuPG\\bin\\gpg.exe.\n\nNow that GitKraken knows about GPG, you can press “Generate”, with an optional passphrase.\n\n\n\nAfter a few seconds, you will now have a GPG signing key! The “Signing Key” field of GitKraken’s GPG Preferences screen is now populated with your new key.\n\n\n\nMake sure to tick both the “Sign Commits by Default” and “Sign Tags by Default” checkboxes, so all future actions are signed. You should end up with a preferences screen like this:\n\n\n\nYour GitKraken is now configured to use commit verification! Time to sort out GitHub…\n\nAdding your GPG key to GitHub\n\n\n  Click “Copy GPG Public Key” in the GitKraken GPG Preferences screen. This will copy your public key to your clipboard, ready to give to GitHub.\n  Go to GitHub’s “Add new GPG key” screen.\n  Paste in your public key from step 1, and press “Add GPG key”.\n  You may need to reconfirm your password, then it’s been added\n\n\nTesting your new signed commits\n\nTry making a commit, you should now see a green icon next to your commit hash in GitKraken. You can mouseover it for more information about your signed commit:\n\n\n\nWhen you push this commit, GitHub will also reflect your verified commit status:\n\n\n\nYour future commits are now all verified!\n\nConsidering how popular GitKraken is becoming (it’s my personal client of choice), being able to implement commit signing so easily provides yet another reason to switchover. Going forward, I fully intend to verify all my commits, with no extra effort beyond the original setup!\n"
    } ,
  
    {
      "tags"     : "Gradle, Settings",
      "title"    : "Automatically adding build time to your Android app",
      "excerpt"  : "When releasing an Android app, it can be useful to show your users the current version name (BuildConfig.VERSION_NAME) or code (BuildConfig.VERSION_CODE). Another nice feature is showing when this version of the app was built, to reassure users that features / bug fixes are being released frequently.\n",
      "url"      : "/automatically-adding-build-time-to-your-android-app/",
      "date"     : "Mar 18, 2019",
      "content"  : "When releasing an Android app, it can be useful to show your users the current version name (BuildConfig.VERSION_NAME) or code (BuildConfig.VERSION_CODE). Another nice feature is showing when this version of the app was built, to reassure users that features / bug fixes are being released frequently.\n\nLuckily, this can be done in 2 super simple steps:\n\nFirst, add BUILD_TIME (of type Date) into your app-level build.gradle, with a value defined using the Date constructor with the current time. So, inside defaultConfig:\n\nbuildConfigField \"java.util.Date\", \"BUILD_TIME\", \"new java.util.Date(\" + System.currentTimeMillis() + \"L)\"\n\n\nNext, just use BuildConfig.BUILD_TIME whenever you want to access this date object. Just like a normal Date object, it can be formatted (e.g. to “18 Mar 2019”):\n\nSimpleDateFormat(\"dd MMM yyy\", Locale.US).format(BuildConfig.BUILD_TIME)\n\n\nThat’s it!\n\nThis technique is used in my open source APOD Wallpaper app, and available as a Gist.\n"
    } ,
  
    {
      "tags"     : "Kotlin, Settings, SharedPreferences",
      "title"    : "Creating a preference utility to safely handle Android SharedPreferences",
      "excerpt"  : "Saving and retrieving shared preference values in Android is relatively straightforward, but doing it safely can be problematic. For example, you may set a default value, then accidentally use a different default value when retrieving!\n",
      "url"      : "/creating-a-preference-utility-to-safely-handle-android-sharedpreferences/",
      "date"     : "Mar 5, 2019",
      "content"  : "Saving and retrieving shared preference values in Android is relatively straightforward, but doing it safely can be problematic. For example, you may set a default value, then accidentally use a different default value when retrieving!\n\nThis post will cover creating PreferenceHelper, a class to safely access preferences of any type. There is also a related post covering creating a preferences screen in your app.\n\nThis entire post is available as a Gist, and as an example preferences project.\n\nCreating strings\n\nFor the PreferenceHelper class, every preference must have both a key, and a default value. These should be stored in an xml file so they can be referenced easily (e.g. by the UI). For example, two boolean preferences may result in the following inside strings.xml:\n\n&lt;string name=\"pref_boolean1\"&gt;boolean1&lt;/string&gt;\n&lt;bool name=\"pref_boolean1_default\"&gt;false&lt;/bool&gt;\n&lt;string name=\"pref_boolean2\"&gt;boolean2&lt;/string&gt;\n&lt;bool name=\"pref_boolean2_default\"&gt;false&lt;/bool&gt;\n\n\nCreating preference utility\n\nThe PreferenceHelper class needs to be constructed with a context, as preferences cannot be saved / retrieved without one. This is due to the looking up of strings which takes place, as well as context being needed for the SharedPreferences themselves. The class also keeps a reference to the shared preferences to be used for all actions.\n\nFor each data type (just boolean, string, and integer in this example), 3 things are needed:\n\n\n  An enum of all preferences of this type, defining both the preference’s key and default value.\n  A getter, which can be passed an enum to return either the saved value or the predetermined default value.\n  A setter, which can be passed an enum as well as a value, to then save that value.\n\n\nFor example, if an app has just 2 boolean options (called boolean1 and boolean2), this will be the code for PreferenceHelper:\n\nclass PreferenceHelper(val context: Context) {\n    val prefs = PreferenceManager.getDefaultSharedPreferences(context)\n\n    enum class BooleanPref(val prefId: Int, val defaultId: Int) {\n        setting1(R.string.pref_boolean1, R.bool.pref_boolean1_default),\n        setting2(R.string.pref_boolean2, R.bool.pref_boolean2_default)\n    }\n\n    fun getBooleanPref(pref: BooleanPref) =\n        prefs.getBoolean(context.getString(pref.prefId), context.resources.getBoolean(pref.defaultId))\n\n    fun setBooleanPref(pref: BooleanPref, value: Boolean) =\n        prefs.edit().putBoolean(context.getString(pref.prefId), value).commit()\n}\n\n\nThis can of course be easily extended to cover strings and integers, as in this article’s Gist.\n\nUsing utility\n\nAll of that work ends up in a utility that is very, very simple to use, whilst never having any risk of using the wrong default value, wrong data type, etc.\n\nA simple use case where you want to get the value of a boolean, and then change it, then repeat the process with a string, would look like:\n\nval prefHelper = PreferenceHelper(this)\n\nval myBoolean = prefHelper.getBooleanPref(PreferenceHelper.BooleanPref.setting1)\nprefHelper.setBooleanPref(PreferenceHelper.BooleanPref.setting1, false)\n\nval myString = prefHelper.getStringPref(PreferenceHelper.StringPref.setting1)\nprefHelper.setStringPref(PreferenceHelper.StringPref.setting1, \"abc\")\n\n\nAs enums are used for the preferences, it’s impossible to pass a string reference to getBooleanPref, and vice versa. This means preferences can be saved and accessed with complete certainty of their datatype and default value.\n"
    } ,
  
    {
      "tags"     : "Config, SharedPreferences, Strings",
      "title"    : "Using PreferenceFragment to effortlessly handle user settings",
      "excerpt"  : "Handling user settings in an Android app is initially quite straightforward. Most apps use SharedPreferences to save a few booleans or strings, then read these values when necessary.\n",
      "url"      : "/using-preferencefragment-to-effortlessly-handle-user-settings/",
      "date"     : "Mar 4, 2019",
      "content"  : "Handling user settings in an Android app is initially quite straightforward. Most apps use SharedPreferences to save a few booleans or strings, then read these values when necessary.\n\nA downside of this is a lack of safety. You might save the user’s name under “Username”, then retrieve it as “UserName”, resulting in never managing to retrieve the name! You also have to create all the switches, text fields, and sliders yourself. Luckily, PreferenceFragment provides an easy way to safely show and change user preferences.\n\nThere is an entire sample project available on GitHub, (and a Gist) for those that prefer to just see the code. Note that some of the code is in Kotlin, but most is XML.\n\nPreparing your project\n\nWhilst we will be using PreferenceFragment in this example, we’ll actually be using PreferenceFragmentCompat to ensure the app looks great on earlier API versions.\n\nTo add the preference library, add the following to your app-level build.gradle‘s dependencies and perform a Gradle sync:\n\nimplementation 'com.android.support:preference-v7:28.0.0'\n\n\nConfiguring your strings\n\nEvery setting in your list needs to have a few strings defined. I recommend doing this in a separate preferences.xml file, to avoid them mixing with your localised strings, but this is personal preference.\n\nFor booleans and strings, you need 4 things. In this example, we’re configuring a “Use mobile data” boolean switch:\n\n\n  An internal reference (the preference’s name in SharedPreferences), e.g. &lt;string name=\"pref_useMobileData\"&gt;useMobileData&lt;/string&gt;.\n  A default value, e.g. &lt;bool name=\"pref_useMobileData_default\"&gt;false&lt;/bool&gt;.\n  A title to be displayed to the user, e.g. &lt;string name=\"useMobileData_title\"&gt;Use mobile data&lt;/string&gt;.\n  A description to be displayed to the user, e.g. &lt;string name=\"useMobileData_desc\"&gt;Sync on mobile networks as well as wifi&lt;/string&gt;.\n\n\nNotice that the default value isn’t a string, and is the datatype of the preference. For numerical settings, there are a few additional parameters required so that a value slider can be displayed:\n\n\n  The minimum value, e.g. &lt;integer name=\"pref_myInt_min\"&gt;1&lt;/integer&gt;.\n  The maximum value, e.g. &lt;integer name=\"pref_myInt_max\"&gt;10&lt;/integer&gt;.\n  The step value (how much the number can be changed by), e.g. &lt;integer name=\"pref_myInt_step\"&gt;1&lt;/integer&gt;.\n\n\nI’ve previously had problems getting step to be obeyed, but minimum and maximum work reliably. Here’s a complete example of an example integer preference:\n\n&lt;string name=\"pref_int1\"&gt;int1&lt;/string&gt;\n&lt;integer name=\"pref_int1_step\"&gt;1&lt;/integer&gt;\n&lt;integer name=\"pref_int1_min\"&gt;0&lt;/integer&gt;\n&lt;integer name=\"pref_int1_max\"&gt;10&lt;/integer&gt;\n&lt;integer name=\"pref_int1_default\"&gt;10&lt;/integer&gt;\n&lt;string name=\"int1_title\"&gt;Set Int 1&lt;/string&gt;\n&lt;string name=\"int1_desc\"&gt;Change the value of the first integer&lt;/string&gt;\n\n\nConfiguring your preference UI\n\nNow that your strings are all prepared, you can create a UI out of them. Inside the /res/xml/ folder, create an XML file to configure your preferences screen. I’ve named mine preferences_ui.xml.\n\nThis XML file defines a PreferenceScreen root object, and then contains multiple Preference, PreferenceScreen, or PreferenceCategorys. Here’s an example of each in action:\n\n&lt;PreferenceScreen xmlns:android=\"http://schemas.android.com/apk/res/android\"&gt;\n    &lt;PreferenceScreen\n            android:title=\"@string/open_repo_title\"\n            android:icon=\"@drawable/ic_repo\"\n            android:summary=\"@string/open_repo_desc\"&gt;\n        &lt;intent android:action=\"android.intent.action.VIEW\"\n                android:data=\"@string/repo_url\"/&gt;\n    &lt;/PreferenceScreen&gt;\n    &lt;PreferenceCategory android:title=\"Booleans\"&gt;\n        &lt;SwitchPreference\n                android:key=\"@string/pref_boolean1\"\n                android:defaultValue=\"@bool/pref_boolean1_default\"\n                android:title=\"@string/boolean1_title\"\n                android:icon=\"@drawable/ic_one\"\n                android:summary=\"@string/boolean1_desc\"/&gt;\n        &lt;SwitchPreference\n                android:key=\"@string/pref_boolean2\"\n                android:defaultValue=\"@bool/pref_boolean2_default\"\n                android:title=\"@string/boolean2_title\"\n                android:icon=\"@drawable/ic_two\"\n                android:summary=\"@string/boolean2_desc\"/&gt;\n    &lt;/PreferenceCategory&gt;\n&lt;/PreferenceScreen&gt;\n\n\nPreferenceScreen\n\nWhilst a PreferenceScreen is the root of your UI, it can also be used to nest additional screens of preferences inside your main layout. Additionally, it can be used to open a desired URL, such as an app’s code repository (with the URL stored in strings.xml):\n\n&lt;PreferenceScreen\n        android:title=\"@string/open_repo_title\"\n        android:icon=\"@drawable/ic_repo\"\n        android:summary=\"@string/open_repo_desc\"&gt;\n    &lt;intent android:action=\"android.intent.action.VIEW\"\n            android:data=\"@string/repo_url\"/&gt;\n&lt;/PreferenceScreen&gt;\n\n\nPreferenceCategory\n\nWhen dealing with many options, grouping them into categories helps associate related options. To help with this, including preferences inside a PreferenceCategory adds a faint line between itself and other elements, and can also be given a title:\n\n\n\nPreference\n\nPreferences are what handle the actual value changing. There’s a SwitchPreference for booleans, EditTextPreference for strings, and a SeekBarPreference for integers among others. What they all have in common is the following attributes:\n\n\n  android:key: The setting identifier. This should be your internal reference from earlier, e.g. pref_useMobileData.\n  android:defaultValue: The default value. This should be your default value from earlier, e.g. false.\n  android:title: Your title defined earlier.\n  android:summary: Your description defined earlier.\n  android:icon: Whilst optional, adding a drawable reference here makes each setting easily identifiable.\n\n\nSetting up your fragment\n\nNow that your preferences_ui.xml file is all set up, it needs to actually be utilised.\n\nFirst, make a PrefsFragment file that extends PreferenceFragmentCompat. Override onCreatePreferences to set your custom preferences screen:\n\nclass PrefsFragment : PreferenceFragmentCompat() {\n    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {\n        addPreferencesFromResource(R.xml.preferences_ui)\n    }\n}\n\n\nNavigating to your fragment\n\nNext, add a link to your soon-to-be-created settings fragment however you currently utilise fragments. For example, I have a FrameLayout in my XML called fragment_frame, so I replace that with my fragment inside my Activity’s onCreate:\n\noverride fun onCreate(savedInstanceState: Bundle?) {\n    super.onCreate(savedInstanceState)\n    setContentView(R.layout.activity_main)\n    this.supportFragmentManager\n        .beginTransaction()\n        .replace(R.id.fragment_frame, PrefsFragment())\n        .commit()\n}\n\n\nThat’s it! You can now navigate to your settings page, and save and load as many booleans, integers, and strings as you like! However, there’s a lot of extra functionality that you’ll be missing out on…\n\nAdding extra functionality\n\nDependent boolean preferences\n\nandroid:dependency allows a setting to be disabled until another setting has been turned on. This is useful for disabling feature configuration until the setting is enabled. To use it, just add the enabling preference’s key as the dependency value on the preference being enabled. For example, to disable boolean2 unless boolean1 is turned on:\n\n&lt;SwitchPreference\n        android:key=\"@string/pref_boolean1\"\n        android:defaultValue=\"@bool/pref_boolean1_default\"\n        android:title=\"@string/boolean1_title\"\n        android:icon=\"@drawable/ic_one\"\n        android:summary=\"@string/boolean1_desc\"/&gt;\n&lt;SwitchPreference\n        android:key=\"@string/pref_boolean2\"\n        android:defaultValue=\"@bool/pref_boolean2_default\"\n        android:title=\"@string/boolean2_title\"\n        android:icon=\"@drawable/ic_two\"\n        android:dependency=\"@string/pref_boolean1\"\n        android:summary=\"@string/boolean2_desc\"/&gt;\n\n\nListening for preference changes\n\nAnother very useful addition to a preference screen is the ability to react when a setting changes. For example, my APOD Wallpaper app disables background tasks as soon as background sync is turned off.\n\nThis is done by letting the fragment listen to preference change events, then checking the events for the preference that is changed.\n\nFirst, make your PrefsFragment implement SharedPreferences.OnSharedPreferenceChangeListener.\n\nNext, start listening to changes inside onResume and stop listening inside onPause:\n\noverride fun onResume() {\n    super.onResume()\n    preferenceScreen.sharedPreferences.registerOnSharedPreferenceChangeListener(this)\n}\n\noverride fun onPause() {\n    super.onPause()\n    preferenceScreen.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this)\n}\n\n\nFinally, set up your change listener. The key passed to it is the key defined in your preferences XML. The preference can be retrieved with findPreference(key), which can then be checked for type / value (e.g. is SwitchPreference or pref.isChecked). In this example, when the first string preference changes, display the new value in a toast:\n\noverride fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {\n    when (key) {\n        getString(R.string.pref_string1) -&gt; {\n            val pref = findPreference(key) as EditTextPreference\n            Toast.makeText(activity!!, \"String changed to ${pref.text}\", Toast.LENGTH_SHORT).show()\n        }\n    }\n}\n\n\nAdding custom action in preferences\n\nThe final functionality covered is setting up a custom action. For example, you may want a button that displays the current status of the app in an AlertDialog. To set this up, first set up an onPreferenceClickListener inside onCreatePreferences:\n\noverride fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {\n    addPreferencesFromResource(R.xml.preferences_ui)\n    findPreference(getString(R.string.pref_show_values)).onPreferenceClickListener = showValuesListener\n}\n\n\nThis listener can do anything you like, and is an easy way to extend the functionality of your settings page. For example, the APOD Wallpaper app mentioned earlier uses 6 listeners, for everything from giving feedback to viewing current app status.\n\nprivate val showValuesListener = Preference.OnPreferenceClickListener { _ -&gt;\n    val prefHelper = PreferenceHelper(activity!!)\n    AlertDialog.Builder(activity!!)\n        .setTitle(R.string.values_title)\n        .setMessage(R.string.values_text)\n        .setPositiveButton(R.string.values_close) { _, _ -&gt; }\n        .show()\n    true\n}\n\n\nConclusion\n\nFor many applications, just this preference fragment combined with change listeners will be enough to manage user preferences. Using the PreferenceFragment skips a lot of repetitive code involved in making a layout, and allows you to focus on correctly responding when settings change.\n\nThe next post in this series will cover programmatically getting / setting values, using the existing preferences.xml values.\n"
    } ,
  
    {
      "tags"     : "BuildVariants, Gradle",
      "title"    : "How to define BuildConfig values (e.g. server URL) using both build flavor and build type",
      "excerpt"  : "When creating an app, build variants are almost always used to some degree. For example, working on a debug build during development but publishing a release build. These buildTypes are a good way of distinguishing between multiple environments your app may run in. You’ll often have a QA buildType that talks to a different server than your live app. Setting server URLs for each buildType is a very common practice, and is usually enough.\n",
      "url"      : "/how-to-define-buildconfig-values-e-g-server-url-using-both-build-flavor-and-build-type/",
      "date"     : "Mar 1, 2019",
      "content"  : "When creating an app, build variants are almost always used to some degree. For example, working on a debug build during development but publishing a release build. These buildTypes are a good way of distinguishing between multiple environments your app may run in. You’ll often have a QA buildType that talks to a different server than your live app. Setting server URLs for each buildType is a very common practice, and is usually enough.\n\nHowever, some apps have multiple flavours, such as an app that is branded with different colours for multiple clients. The problem arises when these two approaches are combined, and a wildly different server URL is needed for every combination of flavour and buildType.\n\nApproach\n\nThere are a few different solutions to this problem, some more elegant than others. This post will cover an implementation of Alex Kucherenko’s excellent StackOverflow answer. An example implementation project is available on GitHub.\n\nThe core idea of the approach is to define a dictionary of key-value pairs called serverUrl inside each product flavour. This will contain every buildType as a key, and the appropriate server URL as the value. Then, a function will determine the correct URL to use during the build.\n\nIn this example, there are 4 environments (debug, qa, staging, release), and 3 client company flavours (companyA, companyB, companyC) to build for.\n\nDefining values\n\nFirst, for each product flavour the serverUrl dictionary needs to be defined, containing a value for every possible build type. This should go inside the android { part of your app-level build.gradle.\n\nflavorDimensions \"company\"\nproductFlavors {\n    companyA {\n        ext.serverUrl = [\n                debug: \"https://internal.companya-dev.com\",\n                qa: \"https://testing.companya.com\",\n                staging: \"https://beta.companya.com\",\n                release: \"https://api.companya.com\"\n        ]\n    }\n    companyB {\n        ext.serverUrl = [\n                debug: \"https://alpha.test.companyb.net\",\n                qa: \"https://test.companyb.net\",\n                staging: \"https://api.companyb.net\",\n                release: \"https://api.companyb.net\"\n        ]\n    }\n    companyC {\n        ext.serverUrl = [\n                debug: \"http://192.168.0.1:29\",\n                qa: \"http://192.168.0.1:45\",\n                staging: \"http://192.168.0.1:77\",\n                release: \"https://api.companyc.com\"\n        ]\n    }\n}\n\n\nParsing values\n\nNext, a function loops through every possible build variant, and looks up the appropriate value based on the flavour and build type. The BuildConfig constant SERVER_URL is then assigned this value, and can be accessed with BuildConfig.SERVER_URL. The function also goes inside android {:\n\napplicationVariants.all { variant -&gt;\n    def flavor = variant.productFlavors[0]\n    variant.buildConfigField \"String\", \"SERVER_URL\", \"\\\"${flavor.serverUrl[variant.buildType.name]}\\\"\"\n}\n\n\nNext steps\n\nThis approach can be used for much more than just server URLs, and the BuildConfig setting function is generic enough that new build variant specific variables can be added just by adding a new line.\n\nNote that some alternative approaches use large if / else trees, by checking what the final build name starts with or contains. An issue with this is if you assume any build with “qa” in should get a QA url, what happens if you make a version for a client called “Kwiqapps”? They’re always going to get QA builds! The approach in this post is safe to use, regardless of the flavour or build type name.\n\nShoutout to David Medenjak, who posted a very similar approach I came across just as I was finishing this article!\n"
    } ,
  
    {
      "tags"     : "Design, SVG, Vector Drawable",
      "title"    : "How to add padding to an Android vector drawable",
      "excerpt"  : "When adding icons to Android apps, you’ll generally be working with square icons. For example, the excellent built-in vector icon library (also available online) only contains perfectly square icons.\n",
      "url"      : "/how-to-add-padding-to-an-android-vector-drawable/",
      "date"     : "Feb 25, 2019",
      "content"  : "When adding icons to Android apps, you’ll generally be working with square icons. For example, the excellent built-in vector icon library (also available online) only contains perfectly square icons.\n\nSometimes however, these vector icons are used in a non-square place. With a normal image file adding extra padding is easy, not so with a vector file!\n\nThis tutorial will cover how to modify a square vector image to add any padding you want, without any changes to your app’s layouts. The icon used is a white access_time, used to represent a loading state.\n\nIn my app, a StaggeredGridLayoutManager is used to display 3 movie posters per row. These movie posters are always the same size, and a ratio of 1:1.5 width:height.\n\nUsing the icon\n\nIf the ImageViews are initially set to our loading icon (either as a default image or a Picasso placeholder), the size difference is immediately obvious:\n\n\n\n&lt;vector android:height=\"24dp\"\n    android:viewportHeight=\"24.0\" android:viewportWidth=\"24.0\"\n    android:width=\"24dp\" xmlns:android=\"http://schemas.android.com/apk/res/android\"&gt;\n    &lt;path android:fillColor=\"#FFFFFF\" android:pathData=\"M11.99,2C6.47,2 2,6.48 2,12s4.47,10 9.99,10C17.52,22 22,17.52 22,12S17.52,2 11.99,2zM12,20c-4.42,0 -8,-3.58 -8,-8s3.58,-8 8,-8 8,3.58 8,8 -3.58,8 -8,8zM12.5,7H11v6l5.25,3.15 0.75,-1.23 -4.5,-2.67z\"/&gt;\n&lt;/vector&gt;\n\n\nResizing our vector drawable\n\nOur vector image is too small! This is due to the android:height=\"24dp\" android:width=\"24dp\" initially included in the icon, enforcing a maximum size. Setting these both to 240dp fixes the horizontal spacing issue, but the 1:1 ratio conflicts with the movie poster’s 1:1.5. This results in the movie posters constantly pushing each other and the loading icons around as they load, making for a very unappealing UI.\n\n\n\n&lt;vector android:height=\"240dp\"\n    android:viewportHeight=\"24.0\" android:viewportWidth=\"24.0\"\n    android:width=\"240dp\" xmlns:android=\"http://schemas.android.com/apk/res/android\"&gt;\n    &lt;path android:fillColor=\"#FFFFFF\" android:pathData=\"M11.99,2C6.47,2 2,6.48 2,12s4.47,10 9.99,10C17.52,22 22,17.52 22,12S17.52,2 11.99,2zM12,20c-4.42,0 -8,-3.58 -8,-8s3.58,-8 8,-8 8,3.58 8,8 -3.58,8 -8,8zM12.5,7H11v6l5.25,3.15 0.75,-1.23 -4.5,-2.67z\"/&gt;\n&lt;/vector&gt;\n\n\nAdjusting the ratio of our vector drawable\n\nSo, the drawable needs to be resized so it is the same ratio as the eventual real content. For example, a width of 200 would require a height of 300. Making these changes stops the movie posters / loading icons pushing each other around, but the icon has become stretched!\n\n\n\n&lt;vector android:height=\"300dp\"\n    android:viewportHeight=\"24.0\" android:viewportWidth=\"24.0\"\n    android:width=\"200dp\" xmlns:android=\"http://schemas.android.com/apk/res/android\"&gt;\n    &lt;path android:fillColor=\"#FFFFFF\" android:pathData=\"M11.99,2C6.47,2 2,6.48 2,12s4.47,10 9.99,10C17.52,22 22,17.52 22,12S17.52,2 11.99,2zM12,20c-4.42,0 -8,-3.58 -8,-8s3.58,-8 8,-8 8,3.58 8,8 -3.58,8 -8,8zM12.5,7H11v6l5.25,3.15 0.75,-1.23 -4.5,-2.67z\"/&gt;\n&lt;/vector&gt;\n\n\nAdding padding inside our resource\n\nThe solution is to add padding to our vector drawable, to keep the original 1:1 ratio. This is done by adding a &lt;group&gt; around the &lt;path&gt;. This group will scale the content inside it (the actual icon), without affecting the overall size / ratio of the vector.\n\nSince the scaleX and scaleY parameters are relative, they must be set to 1 or less to avoid cropping. For example, setting scaleX to 0.99 and scaleY to 0.66 will obey the 1:1.5 ratio required. Note that pivotX and pivotY set the centre point of the scaling, and should be half of your viewpointWidth and viewpointHeight (e.g. 12).\n\n\n\n&lt;vector android:height=\"300dp\"\n    android:viewportHeight=\"24.0\" android:viewportWidth=\"24.0\"\n    android:width=\"200dp\" xmlns:android=\"http://schemas.android.com/apk/res/android\"&gt;\n    &lt;group\n        android:scaleX=\"0.99\"\n        android:scaleY=\"0.66\"\n        android:pivotX=\"12\"\n        android:pivotY=\"12\"&gt;\n        &lt;path android:fillColor=\"#FFFFFF\" android:pathData=\"M11.99,2C6.47,2 2,6.48 2,12s4.47,10 9.99,10C17.52,22 22,17.52 22,12S17.52,2 11.99,2zM12,20c-4.42,0 -8,-3.58 -8,-8s3.58,-8 8,-8 8,3.58 8,8 -3.58,8 -8,8zM12.5,7H11v6l5.25,3.15 0.75,-1.23 -4.5,-2.67z\"/&gt;\n    &lt;/group&gt;\n&lt;/vector&gt;\n\n\nFinally, it looks reasonable! Note that if we wanted more padding on the sides, a scaleX of 0.8 and scaleY of 0.4 would increase the padding on all sides.\n\nHopefully this tutorial has showed how group can be to scale the content of an SVG down. This technique can even be applied to individual parts of an SVG if there are multiple paths!\n"
    } ,
  
    {
      "tags"     : "Dependencies, Modules",
      "title"    : "How to share dependencies in a multi-module Android app",
      "excerpt"  : "Note: This post is a tidied up version of my answer to a StackOverflow question about structuring multi-module apps.\n",
      "url"      : "/how-to-share-dependencies-in-a-multi-module-android-app/",
      "date"     : "Feb 22, 2019",
      "content"  : "Note: This post is a tidied up version of my answer to a StackOverflow question about structuring multi-module apps.\n\nTransitioning to a multi-module project is an excellent way to increase code reuse, optimise build times (unchanged modules aren’t recompiled), and ensure your app’s structure is logical. Your core goal is to make your appmodule as small as possible, as it will be recompiled every time.\n\nWe used a few general principles, which may help you:\n\n\n  A common base-ui module contains the primary strings.xml, styles.xml etc.\n  Other front-end modules (profile, dashboard, etc) implement this base-ui module.\n  Libraries that will be used in all user-facing modules are included in base-ui, as an api instead of implementation.\n  Libraries that are only used in some modules are dependencies only in those modules.\n  The project makes extensive use of data syncing etc too, so there are also base-data, dashboard-data etc modules, following the same logic.\n  The dashboard feature module depends on dashboard-data.\n  The app module depends only on feature modules, dashboard, profile, etc.\n\n\nI strongly suggest sketching out your module dependency flow beforehand, we ended up with ~15 or so modules, all strictly organised. In your case, you mentioned it’s already quite a large app, so I imagine app needs feature modules pulled out of it, as does domain. Remember, small modules mean less code recompiled!\n\nWe encountered some issues with making sure the same version (buildType, flavors) of the app is used across all submodules. Essentially, all submodules have to have the same flavors and buildTypes defined as the app module.\n\nOn the other side of the coin, multi module development does really make you think about dependencies, and enforces strict separation between features. You’re likely to run into a few unexpected problems that you’ve never considered before. For example, something as simple as displaying the app’s version suddenly complicates.\n\nThis article also helped us decide on our approach. There are other excellent articles around nowadays, which I wish had existed when we’d transitioned!\n\nHere’s an example diagram for an app I’m currently working on. Whilst it is far from perfect (the real world unfortunately intrudes!), all of the principles outlined above are visible:\n\n\n\nNote that distinguishing between api and implementation would be a good next step for a diagram like this, so that dependencies are more obvious.\n"
    } ,
  
    {
      "tags"     : "Colours, Custom Flavours, Styles",
      "title"    : "How to handle colours logically in a multi-flavour Android app",
      "excerpt"  : "Handling colours in Android apps is generally pretty straightforward, as simple hex codes are used. However, standardising these across the entire app can be an easily ignored task, one which is essential for multi-flavour apps. Correctly utilising colours allows a single codebase to produce app flavours with radically different colours, e.g. to match company branding.\n",
      "url"      : "/how-to-handle-colours-logically-in-a-multi-flavour-android-app/",
      "date"     : "Feb 21, 2019",
      "content"  : "Handling colours in Android apps is generally pretty straightforward, as simple hex codes are used. However, standardising these across the entire app can be an easily ignored task, one which is essential for multi-flavour apps. Correctly utilising colours allows a single codebase to produce app flavours with radically different colours, e.g. to match company branding.\n\nThese article will walk through 4 “levels” of colour abstraction, in order from worst to best. A simple level 4 project using 2 app flavours is available as a GitHub repo. Please note that these levels are by no means a standard, they’re based entirely on my own experience.\n\nLevel 1: Colour codes in layouts\n\nJust putting hex colour codes in your layout is the easiest way to immediately see results, but isn’t at all sustainable. If you want to change a colour in the future, you’ll have to find and replace every instance of the hex code, and make sure there’s not any other uses of that hex code. Not at all reliable! It’s also not possible to provide different colours for different app flavours.\n\n&lt;TextView\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"wrap_content\"\n    android:text=\"I'm just using the hex codes!\"\n    android:background=\"#FFFFFF\"\n    android:textColor=\"#00000\"/&gt;\n\n\nLevel 2: Colour names in layouts\n\nA massive improvement over level 1 is extracting all colours to a dedicated colors.xml file. This ensures that if you decide to change a colour in the future, at least all instances of it will be changed. Additionally, app flavours can now be used to give different definitions for a colour. For example, flavour A can define “white” as a different hex code to flavour B, just by placing a new colors.xml in that flavour’s source set.\n\nHowever, “white” still has to be… white, unless you want to end up with very confusing layouts! The next level will improve on this approach.\n\nMore information on product flavors is available in the official documentation.\n\n&lt;TextView\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"wrap_content\"\n    android:text=\"I'm using colors.xml!\"\n    android:background=\"@color/white\"\n    android:textColor=\"@color/black\"/&gt;\n\n\n&lt;resources&gt;\n    &lt;color name=\"white\"&gt;#FFFFFF&lt;/color&gt;\n    &lt;color name=\"black\"&gt;#000000&lt;/color&gt;\n&lt;/resources&gt;\n\n\nLevel 3: Purpose names in layouts\n\nAn improvement essential to any multi-flavour project that has multiple colour schemes is nesting colour names, with the purpose-named colour referencing a colour-named colour. This can be tricky to explain textually, an example will make more sense:\n\n&lt;TextView\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"wrap_content\"\n    android:text=\"I'm using purpose names!\"\n    android:background=\"@color/textBackground\"\n    android:textColor=\"@color/textForeground\"/&gt;\n\n\n&lt;resources&gt;\n    &lt;color name=\"white\"&gt;#FFFFFF&lt;/color&gt;\n    &lt;color name=\"black\"&gt;#000000&lt;/color&gt;\n    &lt;color name=\"textBackground\"&gt;@color/white&lt;/color&gt;\n    &lt;color name=\"textForeground\"&gt;@color/black&lt;/color&gt;\n&lt;/resources&gt;\n\n\nThis may seem counter-intuitive, but it has a major advantage: textBackground can now be defined in an app flavour’s colors.xml as any colour, whilst still ensuring a pre-defined palette is stuck to.\n\nFor this approach, the colors.xml file must be split into two parts:\n\n\n  A limited list of colours, with hex codes, for the flavour’s internal palette. These should not be defined in any layouts, and only be referenced by other colours. An easy way to ensure this is to give them colours unique to that flavour (e.g. MyCompanyWhite), as other flavours won’t contain this colour so will fail to build.\n  A lengthy list of areas that need colouring, referencing the internal palette colours. These should be used in all layouts, and it’s absolutely fine if multiple colours reference the same internal palette colour.\n\n\nFor example, textColour, titleColour, and subtitleColour may all reference MyCompanyBlue, defined as #003791. Whilst MyCompany wants them all the same colour, OtherCompany may want titles a different colour. With this approach, this can be accomplished easily without impacting any other flavours of the app.\n\nIn a current project of mine, the company’s internal palette consists of ~10 colours. These definitions are used for over 150 areas that need colouring, allowing fine-grained control over app theming. Make sure to name your colours according to a predefined system, or it’ll get out of control quickly!\n\nLevel 4: Use names in styles\n\nThe final level of logically storing colours is to extract them into styles.xml. For example, using the same TextView as before:\n\n&lt;TextView\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"wrap_content\"\n    android:text=\"I'm using styles!\"\n    style=\"@style/bodyText\"/&gt;\n\n\n&lt;resources&gt;\n    &lt;color name=\"white\"&gt;#FFFFFF&lt;/color&gt;\n    &lt;color name=\"black\"&gt;#000000&lt;/color&gt;\n    &lt;color name=\"textBackground\"&gt;@color/white&lt;/color&gt;\n    &lt;color name=\"textForeground\"&gt;@color/black&lt;/color&gt;\n&lt;/resources&gt;\n\n\n&lt;resources&gt;\n    &lt;style name=\"bodyText\" parent=\"android:Widget.TextView\"&gt;\n        &lt;item name=\"android:background\"&gt;@color/textBackground&lt;/item&gt;\n        &lt;item name=\"android:textColor\"&gt;@color/textForeground&lt;/item&gt;\n    &lt;/style&gt;\n&lt;/resources&gt;\n\n\nNow, all TextViews will use the same abstracted colours by default (so long as the style is applied). Even better, these can easily be changed without manually fixing the colours defined on them all. Styles can (and should) be used for much, much more than just colours, but this example is keeping it simple!\n\nAs a follow-on, it is possible to make all TextViews automatically use a style, very useful in some cases.\n\nConclusion\n\nIt’s worth pointing out that these level definitions are only a pattern I’ve personally found to work well on multi-flavour projects. I’m always interested in alternative approaches, as I find multi-flavour development one of the most challenging but fascinating parts of Android development!\n\nAn example project is available for this post, which provides two different flavours with radically different colour schemes, using level 4:\n\n\n"
    } ,
  
    {
      "tags"     : "Nanodegree, Qualification, Udacity",
      "title"    : "Android Developer Nanodegree enrollment closes soon!",
      "excerpt"  : "Just a quick notice that entry to Udacity’s Android Developer nanodegree closes in around 32 hours after this post is published!\n",
      "url"      : "/android-developer-nanodegree-enrollment-closes-soon/",
      "date"     : "Feb 11, 2019",
      "content"  : "Just a quick notice that entry to Udacity’s Android Developer nanodegree closes in around 32 hours after this post is published!\n\nThe program will walk you through all the steps to creating and publishing your own apps. It is intended for those with Java experience who want to evolve their knowledge into the Android ecosystem. You will receive guidance and support from peer review on all projects, and help with your résumé, LinkedIn, and GitHub profiles. The nanodegree is created in partnership with Google, ensuring that employers will recognize it as a useful qualification.\n\nWhilst the suggested degree length is 8 months, steps are completed at your own pace. This means that those who already have Android experience can likely finish within a few months. Whilst the price is relatively high (£799 for term 1 &amp; £799 for term 2), it’s a reasonable way to invest in your future, especially if your employer will fund the training.\n\nThe classroom opens February 12, 2019, and requires Java, Git, and GitHub experience beforehand. A full syllabus is available.\n\nNote that this post isn’t sponsored at all, I’m just hoping to have more people on the course to discuss assignments with!\n\nEnroll here.\n"
    } ,
  
    {
      "tags"     : "RecyclerView, Sticky Headers, ViewHolder",
      "title"    : "Using StickyLayoutManager to give your RecyclerView sticky headers",
      "excerpt"  : "Once you’ve created a RecyclerView with headers and content, it’s often useful to have the headers “sticky”. Sticky headers will display over the top of your content, and help your app’s users keep track of which section they are currently in.\n",
      "url"      : "/using-stickylayoutmanager-to-give-your-recyclerview-sticky-headers/",
      "date"     : "Jan 30, 2019",
      "content"  : "Once you’ve created a RecyclerView with headers and content, it’s often useful to have the headers “sticky”. Sticky headers will display over the top of your content, and help your app’s users keep track of which section they are currently in.\n\nThis tutorial will cover adding sticky headers to your existing implementation in just a few lines using qiujayen’s Sticky-LayoutManager library. If you haven’t yet created a RecyclerView, I’ve previously written a tutorial on creating RecyclerViews with multiple content types which may be useful.\n\nAdding StickyLayoutManager library\n\nFirst, add jitpack to your project-level build.gradle:\n\nallprojects {\n    repositories {\n        ...\n        maven { url 'https://jitpack.io' }\n    }\n}\n\n\nNext, add the Sticky Layout Manager library to your app-level build.gradle:\n\ndependencies {\n    implementation 'com.github.qiujayen:sticky-layoutmanager:1.0.1'\n}\n\n\nAdding stickiness based on type\n\nFirst, make your RecyclerView adapter (e.g. ContentAdapter in the previous tutorial) implement StickyHeaders:\n\nclass ContentAdapter() : RecyclerView.Adapter&lt;RecyclerView.ViewHolder&gt;(), StickyHeaders {\n\n\nNext, implement the required isStickyHeader(position: Int) function. In this case, if a row is a HeaderRow, it should be sticky:\n\noverride fun isStickyHeader(position: Int) = rows[position] is HeaderRow\n\n\nFinally, actually set the RecyclerView‘s layout manager to StickyHeadersLinearLayoutManager, with a type of your adapter, and a context:\n\nrecyclerView.adapter = ContentAdapter()\nrecyclerView.layoutManager = StickyHeadersLinearLayoutManager&lt;ContentAdapter&gt;(this)\n\n\nThat’s it! This tutorial is available as a GitHub repo.\n\n\n"
    } ,
  
    {
      "tags"     : "Kotlin, RecyclerView, ViewHolder",
      "title"    : "Creating a RecyclerView with multiple content types and layouts in Kotlin",
      "excerpt"  : "RecyclerViews are a little bit complicated to get started with, but almost every app has one or two of them somewhere. One of the first problems you may encounter when using them is their lack of a built-in way to handle multiple content types. Creating and binding a single layout is very straightforward, but multiple layouts requires a slightly more complex setup.\n",
      "url"      : "/creating-a-recyclerview-with-multiple-content-types-and-layouts-in-kotlin/",
      "date"     : "Jan 29, 2019",
      "content"  : "RecyclerViews are a little bit complicated to get started with, but almost every app has one or two of them somewhere. One of the first problems you may encounter when using them is their lack of a built-in way to handle multiple content types. Creating and binding a single layout is very straightforward, but multiple layouts requires a slightly more complex setup.\n\nThis tutorial will cover setting that up, as well as providing a simple content generator to test your RecyclerView. This entire project, along with all layouts, is available as a Gist, or as a GitHub repo.\n\nSetting up the RecyclerView\n\nFirst, create a simple RecyclerView in an xml layout, e.g. activity_main.xml:\n\n&lt;android.support.v7.widget.RecyclerView\n        android:id=\"@+id/recyclerView\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"match_parent\" /&gt;\n\n\nNext, inside your onCreate (or onCreateView) setup your RecyclerView‘s adapter (source of content), and layout manager (to handle the layout logic). getSampleRows will be covered at the end of this post, it can just be listOf() for now if you want a passing build.\n\noverride fun onCreate(savedInstanceState: Bundle?) {\n    super.onCreate(savedInstanceState)\n    setContentView(R.layout.activity_main)\n    recyclerView.adapter = ContentAdapter(getSampleRows(10))\n    recyclerView.layoutManager = LinearLayoutManager(this)\n}\n\n\nFinally, make a ContentAdapter class that implements the RecyclerView adapter:\n\nclass ContentAdapter(private val rows: List&lt;IRow&gt;) : RecyclerView.Adapter&lt;RecyclerView.ViewHolder&gt;() { }\n\n\nCreating the wrapper classes\n\nIn this example, there will be 3 types of content: Header, Message, and Colour. Each of these types needs a class defined, to hold any associated information. These should all extends a base class, so that a single list of all the content types can be created. Luckily, with Kotlin class creation is incredibly succinct:\n\ninterface IRow\nclass HeaderRow(val date: String, val title: String) : IRow\nclass MessageRow(val message: String) : IRow\nclass ColourRow(val colour: Int) : IRow\n\n\nCreating the view holder layouts\n\nEach of these types should also have an XML layout:\n\nrow_colour.xml:\n\n&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;ImageView\n        xmlns:android=\"http://schemas.android.com/apk/res/android\"\n        android:id=\"@+id/colour\"\n        android:layout_height=\"50dp\"\n        android:layout_width=\"match_parent\" /&gt;\n\n\nrow_header.xml:\n\n&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;android.support.constraint.ConstraintLayout\n        xmlns:android=\"http://schemas.android.com/apk/res/android\"\n        xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"50dp\"\n        android:background=\"@android:color/black\"&gt;\n    &lt;TextView\n            android:id=\"@+id/title\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            app:layout_constraintStart_toStartOf=\"parent\"\n            app:layout_constraintTop_toTopOf=\"parent\"\n            app:layout_constraintBottom_toBottomOf=\"parent\"\n            android:paddingStart=\"10dp\"\n            android:textColor=\"@android:color/white\"\n            android:textSize=\"18sp\"/&gt;\n    &lt;TextView\n            android:id=\"@+id/date\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            app:layout_constraintEnd_toEndOf=\"parent\"\n            app:layout_constraintStart_toEndOf=\"@id/title\"\n            app:layout_constraintTop_toTopOf=\"parent\"\n            app:layout_constraintBottom_toBottomOf=\"parent\"\n            app:layout_constraintHorizontal_bias=\"1.0\"\n            android:paddingEnd=\"10dp\"\n            android:textColor=\"@android:color/white\"\n            android:textSize=\"18sp\"/&gt;\n&lt;/android.support.constraint.ConstraintLayout&gt;\n\n\nrow_message.xml:\n\n&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;android.support.constraint.ConstraintLayout \n    xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"wrap_content\"\n    android:padding=\"10dp\"&gt;\n    &lt;TextView \n            android:id=\"@+id/message\" \n            android:layout_width=\"wrap_content\" \n            android:layout_height=\"wrap_content\" /&gt;\n&lt;/android.support.constraint.ConstraintLayout&gt;\n\n\nCreating the view holder classes\n\nEach content type’s ViewHolder should map the UI elements that need to be populated to a local variable that can be referenced later:\n\nclass HeaderViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {\n    val dateView: TextView = itemView.findViewById(R.id.date)\n    val titleView: TextView = itemView.findViewById(R.id.title)\n}\n\nclass MessageViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {\n    val messageView: TextView = itemView.findViewById(R.id.message)\n}\n\nclass ColourViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {\n    val colourView: ImageView = itemView.findViewById(R.id.colour)\n}\n\n\nDefining a constant for each type simplifies the process of creating and binding ViewHolders based on content type:\n\ncompanion object {\n    private const val TYPE_HEADER = 0\n    private const val TYPE_MESSAGE = 1\n    private const val TYPE_COLOUR = 2\n}\n\n\nonCreateViewHolder should inflate a different layout (and use a different ViewHolder) depending on the content type constant. In this case:\n\noverride fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = when (viewType) {\n        TYPE_HEADER -&gt; HeaderViewHolder(LayoutInflater.from(parent.context)\n            .inflate(R.layout.row_header, parent, false))\n        TYPE_MESSAGE -&gt; MessageViewHolder(LayoutInflater.from(parent.context)\n            .inflate(R.layout.row_message, parent, false))\n        TYPE_COLOUR -&gt; ColourViewHolder(LayoutInflater.from(parent.context)\n            .inflate(R.layout.row_colour, parent, false))\n        else -&gt; throw IllegalArgumentException()\n    }\n\n\nBinding the view holder\n\nFirst, the type of the content has to be determined. This can be done by passing the type as a field along with each piece of content, but my preferred approach is using type checking. For example, where rows is the content to be displayed:\n\noverride fun getItemViewType(position: Int): Int =\n    when (rows[position]) {\n        is HeaderRow -&gt; TYPE_HEADER\n        is MessageRow -&gt; TYPE_MESSAGE\n        is ColourRow -&gt; TYPE_COLOUR\n        else -&gt; throw IllegalArgumentException()\n    }\n\n\nNext, now that the content type has been determined, a view holder has to be passed by onBindViewHolder to the appropriate onBind function:\n\noverride fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) =\n    when (holder.itemViewType) {\n        TYPE_HEADER -&gt; onBindHeader(holder, rows[position] as ContentAdapter.HeaderRow)\n        TYPE_MESSAGE -&gt; onBindMessage(holder, rows[position] as ContentAdapter.MessageRow)\n        TYPE_COLOUR -&gt; onBindColour(holder, rows[position] as ContentAdapter.ColourRow)\n        else -&gt; throw IllegalArgumentException()\n    }\n\n\nEach of these onBind functions exists solely to retrieve data from the row item, and set it in the ViewHolder‘s UI element classes:\n\nprivate fun onBindHeader(holder: RecyclerView.ViewHolder, row: HeaderRow) {\n    val headerRow = holder as HeaderViewHolder\n    headerRow.titleView.text = row.title\n    headerRow.dateView.text = row.date\n}\n\nprivate fun onBindMessage(holder: RecyclerView.ViewHolder, row: MessageRow) {\n    (holder as MessageViewHolder).messageView.text = row.message\n}\n\nprivate fun onBindColour(holder: RecyclerView.ViewHolder, row: ColourRow) {\n    (holder as ColourViewHolder).colourView.setBackgroundColor(row.colour)\n}\n\n\nFinally, standard RecyclerView functions also have to be implemented:\n\noverride fun getItemCount() = rows.count()\n\n\nAdding example RecyclerView content\n\nFor this project, a simple random content creator was made. It generates random integers in a range, random dates in a range, random letter combinations, random UUIDs, and random colours:\n\nclass Randomiser {\n    companion object {\n        fun int(min: Int, max: Int): Int {\n            return (min..max).shuffled().last()\n        }\n\n        fun date(): String {\n            val calendar = Calendar.getInstance()\n            calendar.add(Calendar.DAY_OF_YEAR, -int(0, 1000))\n            val format = SimpleDateFormat(\"dd/MM/yyyy\", Locale.UK)\n            return format.format(calendar.time)\n        }\n\n        fun word() = ('a'..'z').map { it }.shuffled().subList(0, 8).joinToString(\"\").capitalize()\n\n        fun message() = UUID.randomUUID().toString()\n\n        fun colour(): Int {\n            val rnd = Random()\n            return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256))\n        }\n    }\n}\n\n\nThis was used to generate a random number of rows for the RecyclerView:\n\nprivate fun getSampleRows(numSections: Int): List&lt;ContentAdapter.IRow&gt; {\n    val rows = mutableListOf&lt;ContentAdapter.IRow&gt;()\n    for (i in 1..numSections) {\n        rows.add(ContentAdapter.HeaderRow(Randomiser.date(), Randomiser.word()))\n        val numChildren = Randomiser.int(0, 10)\n        for (j in 1..numChildren) {\n            if(Randomiser.int(0, 1) &gt; 0) {\n                rows.add(ContentAdapter.MessageRow(Randomiser.message()))\n            } else {\n                rows.add(ContentAdapter.ColourRow(Randomiser.colour()))\n            }\n        }\n    }\n    return rows\n}\n\n\nConclusion\n\nHopefully after checking out the repository or the Gist of this tutorial, the approach makes sense. In general, RecyclerViews are extremely powerful, and should almost always be used when there’s a dynamic list of content to be displayed, whether finite or infinite.\n\nThis approach is easily extendable, and a future post will cover easily adding sticky headers to this RecyclerView implementation. Good luck!\n"
    } ,
  
    {
      "tags"     : "BuildConfig, Gradle, Manifest",
      "title"    : "Adding a variable to both the Android Manifest and Build Config",
      "excerpt"  : "Whilst it is possible to set a variable in your AndroidManifest.xml using manifestPlaceholders and setting the value in your build.gradle, it can often be useful to access these values in your code too. For example, I recently used this post’s technique to define a deep link path (defined in the manifest) and check the url’s path at runtime (checked in the code).\n",
      "url"      : "/adding-a-variable-to-both-the-android-manifest-and-build-config/",
      "date"     : "Jan 22, 2019",
      "content"  : "Whilst it is possible to set a variable in your AndroidManifest.xml using manifestPlaceholders and setting the value in your build.gradle, it can often be useful to access these values in your code too. For example, I recently used this post’s technique to define a deep link path (defined in the manifest) and check the url’s path at runtime (checked in the code).\n\nDefining these variables twice is likely to cause future discrepancies, a much more reliable approach is to set them in the manifest and the code at the same time. Luckily, your build config can store custom values just as well as your manifest!\n\nAdding a new variable\n\nThe main idea behind this approach is creating a function in build.gradle to perform two tasks at once for us at the same time. This addConstantTo function should go inside your defaultConfig { }, and takes 2 parameters; the variable name and variable values:\n\nandroid {\n    defaultConfig {\n        def addConstant = {constantName, constantValue -&gt;\n            manifestPlaceholders += [ (constantName):constantValue]\n            buildConfigField &lt;span class=\"str\"&gt;\"String\", &lt;span class=\"str\"&gt;\"${constantName}\", &lt;span class=\"str\"&gt;\"\\\"${constantValue}\\\"\"\n        }\n        addConstant(&lt;span class=\"str\"&gt;\"DEEPLINK_HOST\", &lt;span class=\"str\"&gt;\"https://blog.jakelee.co.uk\")\n        addConstant(&lt;span class=\"str\"&gt;\"DEEPLINK_PATH\", &lt;span class=\"str\"&gt;\"/deeplink/myprofile\")\n    }\n\n\nThis can then be accessed in your manifest with ${NAME}:\n\n&lt;intent-filter&gt;\n    &lt;action android:name=\"android.intent.action.VIEW\" /&gt;\n    &lt;category android:name=\"android.intent.category.DEFAULT\" /&gt;\n    &lt;category android:name=\"android.intent.category.BROWSABLE\" /&gt;\n    &lt;data\n        android:host=\"${DEEPLINK_HOST}\"\n        android:pathPrefix=\"${DEEPLINK_PATH}\"\n        android:scheme=\"https\" /&gt;\n&lt;/intent-filter&gt;\n\n\nIt can also be accessed in your runtime code at anytime (Kotlin example):\n\nfun isDeeplink() = arguments.data.encodedPath == BuildConfig.DEEPLINK_PATH\n\n\nAdding a flavor / build type dependant variable\n\nThis approach unfortunately won’t work by default if you utilise flavors or build types in your app. For this you need to add a target parameter to your function, inside buildTypes { } or productFlavors { }:\n\ndef addConstantTo = {target, constantName, constantValue -&gt;\n    target.manifestPlaceholders += [ (constantName):constantValue]\n    target.buildConfigField \"String\", \"${constantName}\", \"\\\"${constantValue}\\\"\"\n}\n\n\nThis new target parameter should always be set to owner, the behaviour of other two parameters is unchanged. For example, here’s a usage within product flavors:\n\nproductFlavors {\n    def addConstantTo = {target, constantName, constantValue -&gt;\n        target.manifestPlaceholders += [ (constantName):constantValue]\n        target.buildConfigField \"String\", \"${constantName}\", \"\\\"${constantValue}\\\"\"\n    }\n    flavorone{\n        addConstantTo(owner, \"DEEPLINK_HOST\", \"one.example.com\")\n    }\n    flavortwo{\n        addConstantTo(owner, \"DEEPLINK_HOST\", \"two.example.com\")\n    }\n\n\nHopefully this makes it a bit easier to use flavor / build type specific variables in your apps. A common use is safely setting debug and release remote server URLs. Since the function just performs the same two actions as setting them manually, it’s unlikely to cause any side effects. Note that if you want to store anything besides a String inside your BuildConfig using this you’ll need to further modify the function.\n\nMany thanks to TmTron on StackOverflow for this solution, it’s definitely an underappreciated and elegant solution!\n"
    } ,
  
    {
      "tags"     : "GitHub",
      "title"    : "Setting an emoji only / blank GitHub status",
      "excerpt"  : "\n",
      "url"      : "/setting-an-emoji-only-blank-github-status/",
      "date"     : "Jan 15, 2019",
      "content"  : "\n\nRecently GitHub added user statuses, allowing you to add a little emoji and bit of text under your name on your profile. This is changed either on your profile or in the top right of GitHub, as seen in the screenshot.\n\nAs with other services (e.g. Slack), I wanted to just set an emoji as my status, without any unnecessary text. However, not entering any text (or just a space) in the status field isn’t possible as the “Set status” button is disabled!\n\nTo get around this, copy the character between these two arrows –&gt;⠀&lt;– and paste it into your status. Tada, empty status!\n\nFor example, here’s how it looks on my profile:\n\n\n\nFor those curious, this works because the character between the arrows looks like a space, but isn’t one. It’s actually the braille character for “no dots”, and since it’s part of unicode should work across all platforms that support multiple language sets.\n"
    } ,
  
    {
      "tags"     : "RecyclerView, SharedPreferences, UI",
      "title"    : "Saving and restoring a RecyclerView's position in Android",
      "excerpt"  : "When using a RecyclerView in your Android app, especially one with many (or infinite) items inside it, your users will get pretty frustrated if you fail to remember their position.\n",
      "url"      : "/saving-and-restoring-a-recyclerviews-position-in-android/",
      "date"     : "Jan 8, 2019",
      "content"  : "When using a RecyclerView in your Android app, especially one with many (or infinite) items inside it, your users will get pretty frustrated if you fail to remember their position.\n\nI recently used a RecyclerView to show a few hundred rows, each of which may link to another fragment, returning from which will reinitialise the fragment. With the default implementation, every time the RecyclerView’s Adapter is assigned the position is reset. In this tutorial, I’ll cover how to save, load, and reset this position.\n\nNote that this tutorial will only work if your RecyclerView’s content / order won’t change. Kotlin is used for this article’s code, but the technique also works in Java. It is also available as a GitHub Gist if you’d like to just see the code.\n\nPrerequisities\n\nSince the position restoring framework will be reused, first create an interface ListPositioner.kt:\n\ninterface ListPositioner {\n    val recyclerScrollKey: String\n\n    fun loadListPosition()\n\n    fun saveListPosition()\n\n    fun resetListPosition()\n}\n\n\nNext, make sure your controller class (Fragment, Activity, etc) implements ListPositioner (e.g. MyFragment : ListPositioner).\n\nFinally, we need a SharedPreferences key to store the scroll position in:\n\noverride val recyclerScrollKey = \"uk.co.jakelee.scrollposition\"\n\n\nSaving the RecyclerView’s scroll position\n\nTo save the position, we’re just going to save the first fully visible item’s position into SharedPreferences. First retrieve the scroll position of your RecyclerView (myRecycler in this example), then save it:\n\noverride fun saveListPosition() {\n    val position = (myRecycler.layoutManager as LinearLayoutManager).findFirstCompletelyVisibleItemPosition()\n    PreferenceManager.getDefaultSharedPreferences(activity!!)\n        .edit()\n        .putInt(recyclerScrollKey, position)\n        .apply()\n}\n\n\nNote that apply() saves the preference in the background, if you’re going to be rapidly returning to the RecyclerView you may need commit() as it saves immediately. Additionally, you may find .findFirstVisibleItemPosition() works better in your use case as it depends on average row height somewhat.\n\nLoading the RecyclerView’s scroll position\n\nLoading the scroll position is even simpler, as scrollToPosition() is used:\n\noverride fun loadListPosition() {\n    val scrollPosition = PreferenceManager.getDefaultSharedPreferences(activity!!).getInt(recyclerScrollKey, 0)\n    myRecycler.scrollToPosition(scrollPosition)\n}\n\n\nNote that if you are currently drawing your RecyclerView under the toolbar / other views, you may need to (safely) manually adjust the scrollPosition. “Fully visible” actually only refers to “fully visible somewhere”, even if it is under another view! In my case, the adjustment needed was:\n\noverride fun loadListPosition() {\n    var scrollPosition = PreferenceManager.getDefaultSharedPreferences(activity!!).getInt(recyclerScrollKey, 0)\n    if (scrollPosition &gt; 0 &amp;&amp; scrollPosition &lt; myRecycler.layoutManager.childCount) {\n        scrollPosition++ // To offset the \"completely visible\" item under the action bar\n    }\n    myRecycler.scrollToPosition(scrollPosition)\n}\n\n\nResetting the RecyclerView’s scroll position\n\nFinally, you’ll likely want to regularly reset the scroll position if you change the RecyclerView content, the user logs out, etc. This is done by just resetting the SharedPreference:\n\noverride fun resetSavedListPosition(){\n    PreferenceManager.getDefaultSharedPreferences(activity!!)\n        .edit()\n        .putInt(recyclerScrollKey, 0)\n        .apply()\n}\n\n\nThis post is also available as a GitHub Gist.\n"
    } ,
  
    {
      "tags"     : "Styles, TextView, UI",
      "title"    : "Using break strategy to fix unusual Android TableRow text wrapping issues",
      "excerpt"  : "An easy way of creating simple, aligned layouts in XML is using a TableLayout and TableRows. This works excellently for most situations, but unfortunately has a few quirks when it comes to handling TextView text wrapping. Recently a bug report was received where very long emails addresses weren’t displayed correctly, and flowed offscreen.\n",
      "url"      : "/using-break-strategy-to-fix-unusual-android-text-wrapping-issues/",
      "date"     : "Jan 7, 2019",
      "content"  : "An easy way of creating simple, aligned layouts in XML is using a TableLayout and TableRows. This works excellently for most situations, but unfortunately has a few quirks when it comes to handling TextView text wrapping. Recently a bug report was received where very long emails addresses weren’t displayed correctly, and flowed offscreen.\n\nThis post will cover how to fix the text flowing off screen, and the subsequent wrapping issue encountered. Just for reference, this is how the TextView in a TableRow looked when populated with a long word (in this case an email address):\n\n\n\nA GitHub gist of the solution is also available.\n\nFixing text escaping row\n\nFixing the text flowing off-screen was a simple matter of setting android:layout_weight=\"1\" on the TextView I wanted to wrap, e.g.:\n\n&lt;TableRow\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"&gt;\n    &lt;TextView\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:text=\"@string/Label_Email\" /&gt;\n\n    &lt;TextView\n        android:id=\"@+id/customer_email\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_weight=\"1\" /&gt;\n&lt;/TableRow&gt;\n\n\nThe TableLayout itself should also have android:stretchColumns=\"*\" (or your specific column index), otherwise this fix is less likely to work.\n\n\n\nFixing text not filling TextView\n\nOur text is now wrapping correctly but.. not in the way we’d expect! Despite how it looks, the TextView is correctly taking up all available space (this can be verified by viewing bounds or setting a background colour), it’s the text itself misbehaving.\n\nThis is caused by Android’s default break strategy handling long words poorly. The break strategy determines how a word should be broken if it cannot fit all in one line, and can be simple, balanced (default) or high_quality. balanced is trying to make all lines the same length, which is not really what we want. Instead we want simple, to just start a new line when it’s needed.\n\nSo, just adding android:breakStrategy=\"simple\" to your TextView will make the text wrap as expected. However, this is only available on API levels 23+, so you may want to create a style of this in your styles.xml and apply it to your TextView for API levels &gt; M, so at least those versions wrap correctly:\n\n\n\nHere’s the final XML, for completeness’ sake:\n\n&lt;TableRow\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"&gt;\n    &lt;TextView\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:text=\"@string/Label_Email\" /&gt;\n\n    &lt;TextView\n        android:id=\"@+id/customer_email\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_weight=\"1\"\n        style=\"@style/SimpleBreakStrategy\"/&gt;\n&lt;/TableRow&gt;\n\n\nAnd the associated styles.xml entry:\n\n&lt;style name=\"SimpleBreakStrategy\"&gt;\n    &lt;item name=\"android:breakStrategy\" tools:targetApi=\"m\"&gt;simple&lt;/item&gt;\n&lt;/style&gt;\n\n"
    } ,
  
    {
      "tags"     : "Androidx, Kotlin, Deep Link",
      "title"    : "Accessing a deep link intent's data / URL in a fragment with AndroidX",
      "excerpt"  : "Usually, accessing the data associated with a deep link intent in an Activity is just a case of calling intent.data. Easy!\n",
      "url"      : "/accessing-a-deep-link-intents-data-url-in-a-fragment-with-androidx/",
      "date"     : "Jan 4, 2019",
      "content"  : "Usually, accessing the data associated with a deep link intent in an Activity is just a case of calling intent.data. Easy!\n\nHowever when this intent is forwarded to a fragment (using the AndroidX navigation code below), the intent suddenly becomes much harder to deal with. In the fragment there is no onNewIntent, or even any intent at all. This tutorial will cover how to retrieve the intent’s data, including deep link URL.\n\noverride fun onNewIntent(intent: Intent?) {\n    super.onNewIntent(intent)\n    my_nav_host_fragment.findNavController().onHandleDeepLink(intent)\n}\n\n\nWhen the intent was forwarded to the fragment, it was significantly changed. It has now been packaged into arguments, which contains an ArrayMap called mMap, as well as a few other properties.\n\n\n\nIf you want to access this ArrayMap (for example to access the URL in the deep link), you can just call arguments?.get(yourKey). However, what if you don’t know the key, since there’s no obvious way of looking it up?\n\nIn that case you need to call arguments?.keySet(), to receive an array of the keys the main ArrayMap uses. For example, my intent only had the deep link intent as a key:\n\n\n\nNow that you’ve got your key, you can call arguments?.get(yourKey) as Intent, to get your original intent back! This intent can then be queried as usual, such as .data.encodedPath to get the URL’s path.\n\nHere’s a useful function that can be called in a fragment to determine if the current arguments are from a deep link for your target path:\n\nfun isTargetPath(): Boolean {\n    val deepLinkKey = arguments?.keySet()?.firstOrNull() ?: \"\"\n    if (deepLinkKey.isNotEmpty() &amp;&amp; arguments?.get(deepLinkKey) is Intent) {\n        val targetPath = \"/mytargetpath\"\n        return (arguments?.get(deepLinkKey) as Intent).data.encodedPath == targetPath\n    }\n    return false\n}\n\n\nThis should go in your onViewCreated, to avoid it being called repeatedly if the use pauses / resumes your fragment.\n"
    } ,
  
    {
      "tags"     : "API, APOD, NASA, Postman",
      "title"    : "An introduction to the NASA APOD API",
      "excerpt"  : "NASA’s Astronomy Picture of the Day API is an amazing service providing free, reliably sourced space images. However, the official documentation can be a little lacking, hopefully this post will improve on it somewhat.\n",
      "url"      : "/an-introduction-to-the-nasa-apod-api/",
      "date"     : "Dec 30, 2018",
      "content"  : "NASA’s Astronomy Picture of the Day API is an amazing service providing free, reliably sourced space images. However, the official documentation can be a little lacking, hopefully this post will improve on it somewhat.\n\nI’m currently using the API to create an Android app that changes your wallpaper everyday, so all lessons here were learnt through trial and error. The app isn’t quite finished yet, but already has more features and reliability than all other similar offerings!\n\nPostman collection\n\nEvery request made in this tutorial is available in a Postman collection, so you can start using the API instantly. You’ll need to create an environment variable called api_key with your API key.\n\nTo use the collection, save this link as postman.json, then import it into your Postman collections:\n\n\n\nRequest\n\nTo return an APOD, make a GET request to https://api.nasa.gov/planetary/apod. Whilst the following 4 URL parameters are optional, your requests will almost certainly need a couple of them:\n\n\n  api_key: Using an API key allows you to make up to 1000 requests per hour. If you do not set one, you’ll hit quota limits pretty quickly. You can get one by filling in the simple API key form, you’ll then be emailed an API key within a few minutes.\n  date: This is the date you want to return the APOD for (in YYYY-MM-DD format), if none is set the latest APOD will be returned. Please see the “Limitations” section for more information on this.\n  start_date and end_date: This is an alternative to date, and returns an array of all APODs inside the range.\n  hd: This specifies whether the image’s HD URL should be returned alongside a regular quality URL, and should be set to true or false. However, the API doesn’t seem to always follow this parameter, and sometimes returns the HD URL even if you haven’t asked for it!\n\n\nA fully populated example URL is https://api.nasa.gov/planetary/apod?api_key=xxxxxxxxxxxxxxxxxxxxxxxx&amp;date=2018-12-28, the response for this will be described below.\n\nResponse\n\nThe response is a JSON object (or if using a date range, an array of objects), with some fields always being present and others dependant on the APOD requested. All fields are strings. for example:\n\n{\n   \"copyright\":\"island universe\",\n   \"date\":\"2018-12-28\",\n   \"explanation\":\"Barred spiral galaxy NGC 1365 is truly a majestic island universe some 200,000 light-years across. Located a mere 60 million light-years away toward the chemical constellation Fornax, NGC 1365 is a dominant member of the well-studied Fornax galaxy cluster. This impressively sharp color image shows intense star forming regions at the ends of the bar and along the spiral arms, and details of dust lanes cutting across the galaxy's bright core. At the core lies a supermassive black hole. Astronomers think NGC 1365's prominent bar plays a crucial role in the galaxy's evolution, drawing gas and dust into a star-forming maelstrom and ultimately feeding material into the central black hole.\",\n   \"hdurl\":\"https://apod.nasa.gov/apod/image/1812/NGC1365_HaLRGBpugh.jpg\",\n   \"media_type\":\"image\",\n   \"service_version\":\"v1\",\n   \"title\":\"NGC 1365: Majestic Island Universe\",\n   \"url\":\"https://apod.nasa.gov/apod/image/1812/NGC1365_HaLRGBpugh1024.jpg\"\n}\n\n\n\n  copyright (optional): This field (when present) contains the copyright holder of the image. If the field is not present, the image is public domain.\n  date: This field just returns the date passed in the URL, so is only useful if not defining a target APOD date.\n  explanation: A text description of the photo. This usually contains 100-200 words.\n  hdurl (optional): If requested, this field contains the full quality version of the image. Note that this can be missing, even if you request it!\n  media_type: This field determines the type of content. Usually this is image, but can be video. There may be other media_types, but I haven’t found any.\n  service_version: This has always been v1, but.. could one day change.\n  title: This APOD title is usually 3-6 words long, and is reliably concise, factual, and descriptive.\n  url: This field contains the actual APOD URL. Usually a .jpg, but for non-image APODs may be a YouTube video or another arbitrary URL.\n\n\nLimitations\n\nWhilst the API is an excellent service, it definitely isn’t perfect. The following few sections are things that may be unclear initially, but need to be considered when using the API.\n\nReliability\n\nThe API quite often simply doesn’t work. It’ll return a (HTML) server error page from their CDN after a long delay (20-30 seconds). This usually persists for 5-10 minutes, the API then performs normally again. Luckily, these failed requests don’t seem to use up your quota, but you’ll still need to handle this unusual response.\n\n&lt;html&gt;\n    &lt;head&gt;\n        &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"&gt;\n        &lt;meta charset=\"utf-8\"&gt;\n        &lt;title&gt;Application Error&lt;/title&gt;\n        &lt;style media=\"screen\"&gt;\n\t\t  html,body,iframe {\n\t\t\tmargin: 0;\n\t\t\tpadding: 0;\n\t\t  }\n\t\t  html,body {\n\t\t\theight: 100%;\n\t\t\toverflow: hidden;\n\t\t  }\n\t\t  iframe {\n\t\t\twidth: 100%;\n\t\t\theight: 100%;\n\t\t\tborder: 0;\n\t\t  }\n\t\t&lt;/style&gt;\n    &lt;/head&gt;\n    &lt;body&gt;\n        &lt;iframe src=\"//www.herokucdn.com/error-pages/application-error.html\"&gt;&lt;/iframe&gt;\n    &lt;/body&gt;\n&lt;/html&gt;\n\n\nValid dates\n\nAccording to the APOD archive, the earliest APOD is from 1995-06-16. There are a few missing days since then, requesting any of these (e.g. 1995-06-17) will return a server error:\n\n{\n    \"code\": 500,\n    \"msg\": \"Internal Service Error\",\n    \"service_version\": \"v1\"\n}\n\n\nIt’s also not guaranteed that today’s APOD will be ready at midnight, especially when considering time zones. As such, any implementation should have the ability to handle today’s date not returning results, and potentially falling back to the day before.\n\nNon-image dates\n\nWhilst most days return image URLs, some return video URLs (or potentially other content), determined by the media_type field in the response. For example, 2018-12-23 is a video, and returns the following:\n\n{\n    \"date\": \"2018-12-23\",\n    \"explanation\": \"About 12 seconds into this video, something unusual happens. The Earth begins to rise.  Never seen by humans before, the rise of the Earth over the limb of the Moon occurred 50 years ago tomorrow and surprised and amazed the crew of Apollo 8. The crew immediately scrambled to take still images of the stunning vista caused by Apollo 8's orbit around the Moon. The featured video is a modern reconstruction of the event as it would have looked were it recorded with a modern movie camera. The colorful orb of our Earth stood out as a familiar icon rising above a distant and unfamiliar moonscape, the whole scene the conceptual reverse of a more familiar moonrise as seen from Earth. To many, the scene also spoke about the unity of humanity: that big blue marble -- that's us -- we all live there. The two-minute video is not time-lapse -- this is the real speed of the Earth rising through the windows of Apollo 8. Seven months and three missions later, Apollo 11 astronauts would not only circle Earth's moon, but land on it.\",\n    \"media_type\": \"video\",\n    \"service_version\": \"v1\",\n    \"title\": \"Earthrise: A Video Reconstruction\",\n    \"url\": \"https://www.youtube.com/embed/1R5QqhPq1Ik?rel=0\"\n}\n\n\nImage size\n\nWhilst the url field has reasonably sized images (usually 1000-2000px width / height), the hdurl field can have absolutely massive images. For example, 2018-12-02 returns https://apod.nasa.gov/apod/image/1812/FairyPillar_Hubble_3857.jpg, a 3857×7804 image! There’s certainly larger ones out there, so HD images need to be handled carefully to avoid excessive memory usage.\n\nQuota\n\nYour API key has a default limit of 1000 requests per hour. Every response contains a header X-RateLimit-Remaining with your remaining requests, and a header X-RateLimit-Limit with your current quota.\n\nIf the 1000/hr quota isn’t enough, NASA ask you to contact them for a higher limit, although no contact details are provided!\n\nHeaders\n\nEvery response contains the following headers, although only the X-RateLimit ones are likely to be useful:\n\nServer → openresty\nDate → Fri, 28 Dec 2018 23:51:36 GMT\nContent-Type → application/json\nTransfer-Encoding → chunked\nConnection → keep-alive\nVary → Accept-Encoding\nX-RateLimit-Limit → 1000\nX-RateLimit-Remaining → 979\nVia → 1.1 vegur, http/1.1 api-umbrella (ApacheTrafficServer [cMsSf ])\nAge → 0\nX-Cache → MISS\nAccess-Control-Allow-Origin → *\nStrict-Transport-Security → max-age=31536000; preload\nContent-Encoding → gzip\n\n\nSummary\n\nAs mentioned at the start of this post, NASA’s APOD API is an extremely useful resource, even with it’s faults and quirks.\n\nI strongly recommend you download the Postman collection I created (save as a .json and import) and start playing around yourself!\n"
    } ,
  
    {
      "tags"     : "Design, Font Awesome",
      "title"    : "Creating custom stacked icons with FontAwesome",
      "excerpt"  : "FontAwesome is an excellent resource for web developers, providing almost 1500 icons for free. Whilst these are often enough for your use case, sometimes additional icons are needed. For example, on my portfolio I wanted a square icon for each social media service, but only 6 out of 10 services had a square icon available!\n",
      "url"      : "/creating-custom-square-icons-with-fontawesome/",
      "date"     : "Dec 29, 2018",
      "content"  : "FontAwesome is an excellent resource for web developers, providing almost 1500 icons for free. Whilst these are often enough for your use case, sometimes additional icons are needed. For example, on my portfolio I wanted a square icon for each social media service, but only 6 out of 10 services had a square icon available!\n\nIn this tutorial, I’ll show how to create square icons for any FontAwesome icon, as well as circular, borderless, and a few other variations. A Gist of the approach is available, if you’d just like to see the code.\n\nAs mentioned before, here’s the end goal: 10 matching icons.\n\nIf we’re just using existing FontAwesome icons, we’d end up with the following. Note the 4 mismatching icons!\n\n\n\nThroughout this tutorial, the current progress of the 4 mismatched icons will be shown alongside their final forms, so that every change is immediately obvious.\n\nDisplaying initial icons\n\nFirst, our starting code is an &lt;a&gt; tag (to link to the service), containing an &lt;i&gt; tag (to display the FontAwesome icon):\n\n&lt;a href=\"https://stackoverflow.com/u/608312\" target=\"_blank\"&gt;\n    &lt;i class=\"fab fa-stack-overflow\"&gt;&lt;/i&gt;\n&lt;/a&gt;\n\n\nThis displays a basic icon, in the default link colour for the page (black). The example above is for StackOverflow, when applied to all 4 icons it ends up like this:\n\n\n\nIt’s a start, they’re all clearly much too small and mismatching though!\n\nPreparing for stack\n\nTo prepare for the “stack” used to layer icons with a fixed background, all the icons need to be made larger, and be consistent. To do that, a few FontAwesome classes need to be applied to the parent element, in this case our &lt;a&gt;.\n\nOur code from before now becomes:\n\n&lt;a class=\"fa-stack fa-2x fa-fw\" href=\"https://stackoverflow.com/u/608312\" target=\"_blank\"&gt;\n    &lt;i class=\"fab fa-stack-overflow\"&gt;&lt;/i&gt;\n&lt;/a&gt;\n\n\n\n  fa-stack prepares the icon for stacking. The most noticeable effect of this is an increase in spacing around each icon.\n  fa-2x doubles the size of the icon, since they’re far too small currently.\n  fa-fw sets the icons to be a fixed width, necessary for them to fit in a grid of icons.\n\n\n\n\nWe’re already pretty close! Just need to add the stacked background, and our icons will be ready to go.\n\nImplementing stack\n\nTo implement the stack, a “2x size” and “1x size” icon needs to be defined. In our case, our service icon needs to become 1x, this is done by adding the fa-stack-1x class to it.\n\nAdditionally, it needs inverting (since the background colour is going to be the current text colour), so fa-inverse is also added to the classes.\n\nFinally, a brand new element needs adding; the background. In this example we’re using fa-square behind the icon, so the background is placed before the icon in the code hierarchy. This background also has fa-stack-2x, since it’s going to be larger. The final result is:\n\n&lt;a class=\"fa-stack fa-2x fa-fw\" href=\"https://stackoverflow.com/u/608312\" target=\"_blank\"&gt;\n    &lt;i class=\"fas fa-square fa-stack-2x\"&gt;&lt;/i&gt;\n    &lt;i class=\"fab fa-stack-overflow fa-stack-1x fa-inverse\"&gt;&lt;/i&gt;\n&lt;/a&gt;\n\n\n\n\nAll done! A Gist of my portfolio’s implementation is available if you’d like to see the final version.\n\nAlternative implementations\n\nAll squares\n\nUsing the stack technique for all icons does improve consistency, both in the UI and in the code. For example, replacing fa-linkedin with fa-linkedin-in or fa-github-square with fa-github, then performing all the other steps. However, some services (only IMDb in my case) doesn’t have a non-square icon! Here’s the 10 services, with all the existing square icons converted to stacked square icons:\n\n\n\nAll circles\n\nReplacing all fa-square backgrounds with fa-circle results in the following. Note the IMDb inability to play nicely!\n\n\n\nTower\n\nTo create a “tower” of icons, with no gaps, just replace fa-square with fa-square-full and a &lt;br&gt; between each icon:\n\n\n\nOther shapes\n\nMost FontAwesome shapes work well as a background. Here’s fa- play / certificate / comment / heart / cloud, most of which look pretty good!\n\n\nFurther modifications\n\nSince these icons are using FontAwesome, the usual modifiers can be used, simply by applying additional classes:\n\n\n  Rotating / flipping: fa-rotate-90 / 180 / 270, fa-flip-horizontal / vertical.\n  Spinning: fa-spin.\n\n\nSummary\n\nAs mentioned before, a Gist containing this tutorial’s code is available. Making all brand icons on your site fit a common design helps them feel like a more natural part of your site, instead of just stuck on top. A live implementation is available at the top of my portfolio.\n\nIt’s also worth mentioning FontAwesome’s Pro offering. This provides nearly 3x as many icons, such as outlined and light versions of the square / circle backgrounds. For $60/yr it’s unlikely to be worth it for a single site, but if web developing at all professionally, it’s likely worth it!\n"
    } ,
  
    {
      "tags"     : "Imgur, Screenshot, ShareX, Sharing",
      "title"    : "Using ShareX to take screenshots and upload them to a private Imgur album",
      "excerpt"  : "The ability to quickly share screenshots with others is essential to day to day conversation / work, especially when talking to people in other offices or countries. The built in Windows Snipping Tool has good basic functionality (e.g. press Win + Shift + S to select an area to copy), but lacks any image uploading functionality, or advanced editing.\n",
      "url"      : "/using-sharex-to-take-screenshots-and-upload-them-to-a-private-imgur-album/",
      "date"     : "Dec 28, 2018",
      "content"  : "The ability to quickly share screenshots with others is essential to day to day conversation / work, especially when talking to people in other offices or countries. The built in Windows Snipping Tool has good basic functionality (e.g. press Win + Shift + S to select an area to copy), but lacks any image uploading functionality, or advanced editing.\n\nThis tutorial will let you do the following with ShareX, with one keypress:\n\n\n  Select an area\n  Perform advanced editing (numbering, blurring, pixelating, highlighting, circling etc)\n  Copy the selected area to your clipboard, ready to be pasted\n  Upload the selected area to a private album on Imgur, and provide you a link in a notification if you need it\n\n\nPretty good, for a completely free setup!\n\nInstalling ShareX\n\nFirst, download and install ShareX. It’s also available on Steam.\n\nIt has an absolutely staggering number of features (see gif below), and it’s definitely worth having a look at the included tools if you’re ever looking for a new utility program.\n\n\n\nAnimation from getsharex.com\n\nOnce ShareX is running, it will appear in your toolbar. Double clicking the icon opens the settings screen. Whilst it can be a little confusing to navigate, the following steps will cover all you need for this configuration.\n\nConfiguring clipboard copying\n\nClipboard copying is going to be an “After capture” task. To enable it, click “After capture tasks”, then “Copy image to clipboard”, making sure nothing else is ticked. That’s it!\n\n\n\nConfiguring Imgur uploading\n\nThe next stage is uploading your screenshot to imgur, so that it displays in a popup notification. Clicking this notification opens the image in your default browser, so you can easily copy the URL wherever you need to.\n\n\n\nEnabling Imgur\n\nFirst, under “After capture tasks”, enable “Upload image to host”.\n\nNext, set Imgur as your image host under “Destinations”, “Image Uploader”, then “Imgur”.\n\nConnecting ShareX to Imgur\n\nIn the same “Destinations” menu, open “Destination settings”. You’ll now need to authorise ShareX to access your Imgur account. This is done by:\n\n\n  Select “Account type” of “User”.\n  Click “Step 1: Open authorize page”.\n  This will open your browser. Log in to your Imgur account, and you will be shown a verification code.\n  Copy this code into the “Verification code” text box in ShareX.\n  Click “Step 2: Complete authorization”.\n\n\n\n\nYou’re now connected! Time to get an album set up.\n\nUploading ShareX images to an Imgur album\n\nMake sure “Use direct link” is ticked, then make ShareX upload your images into an album:\n\n\n  Make a new album on imgur with the privacy “Secret”, so that only you can view it.\n  Click “Refresh album list” on the Imgur destination settings in ShareX.\n  Select your newly created folder.\n  Make sure “Upload images to selected album” is ticked.\n\n\n\n\nAdding hotkey\n\nAlmost there! The final necessary step is setting up a hotkey for your task. Set this under “Hotkey settings”, I find F11 to be most convenient but it can be almost anything.\n\n\n\nYour ShareX is now fully setup! Press F11 (or your hotkey), and enjoy your clipboard copying and automatic uploading!\n\nUsing ShareX’s screenshot tool\n\nWhen your hotkey is pressed, the ShareX screenshot tool will popup. Whilst just selecting an area will perform the normal actions, there’s a lot of functionality included which can be very useful. Below is a screenshot of the editor, as well as an explanation of every option, since it can be a little overwhelming.\n\n\n\nMain bar (left to right)\n\n\n  The 3 dot icon lets you move the main bar around the screen.\n  The rectangular icon lets you select a rectangular area to capture (default).\n  The circular icon lets you select a circular / oval area to capture.\n  The odd shaped icon lets you select a custom shape to capture. This can have many points, even overlapping!\n  This rectangular icon lets you select a rectangle to overlay on the screen. Selecting this (or the circular overlay) will display options for outline / fill colour.\n  This circular icon lets you select a circular / oval shape to overlay on the screen.\n  The pen icon lets you draw / write on the captured area.\n  The connected dot icon lets you draw lines between areas in the captured area.\n  The arrow icon lets you draw arrows.\n  The letter “A” lets you add text to the captured area.\n  The letter “A” with a background lets you add text, but with a background.\n  The speech bubble lets you add a speech bubble to the screenshot.\n  The “001” icon lets you start counting. Once enabled, each time you click a new number will appear, one higher than the one before. This is useful for listing steps in a process.\n  The folder icon lets you overlay an existing image into your screenshot.\n  The monitor icon lets you overlay a part of the screen on your screenshot. Yes, really!\n  The emoji icon lets you add a sticker. Google’s blob emojis and a few custom ones are included. The full list is in the source code.\n  The pointer icon lets you display a cursor on your screenshot.\n  The striped area icon lets you blur a selected area.\n  The grid icon lets you pixelate a selected area.\n  The “abc” icon lets you highlight a selected area.\n  This option (and the next) provide options for the currently selected tool, so vary depending on tool.\n  See above.\n  The camera icon lets you change the capture area (screen, area, window).\n  The settings icon lets you customise the editor with options for crosshair, icons to display, etc.\n  Same as #1.\n\n\nAdditional UI\n\n\n  The “crosshair” icon determines where your cursor currently is. Clicking and holding will let you select an area, whilst a single click will upload the whole screen.\n  The “magnifier” lets you zoom in on where your cursor is, to make sure you are getting the perfect pixel.\n  The X and Y coordinates below your magnifier shown help orientate your cursor in the overall window.\n  Additionally, selecting an area shows the below UI, with your cursor’s original X + Y coord, and the selected areas width and height.\n\n\n\n\nSummary\n\nHopefully you’ve now got your ShareX setup with some basic but useful functionality. There’s a lot more customisation available, this is barely scratching the surface, so experiment by yourself! There is some community support available on the Steam forums and on /r/ShareX.\n\nThere’s also lots of included tools, many with further customisation, such as those screenshotted below. Gifs can also be recorded, images saved locally, and all kinds of convoluted workflows setup! I use ShareX for all screenshots on this blog, and find it extremely useful, usually capturing 10-30 images per day.\n\n\n"
    } ,
  
    {
      "tags"     : "Cloudflare, GitHub, verification",
      "title"    : "How to get \"Verified\" tag on your GitHub organization's page",
      "excerpt"  : "Your company’s GitHub profile is a great way to show off some of the high quality work produced internally, and attract new potential developers. Additionally, all the usual benefits of sharing your code with others apply, and you’ll be helping the open source community!\n",
      "url"      : "/how-to-get-a-verified-tag-on-your-github-organizations-page/",
      "date"     : "Dec 21, 2018",
      "content"  : "Your company’s GitHub profile is a great way to show off some of the high quality work produced internally, and attract new potential developers. Additionally, all the usual benefits of sharing your code with others apply, and you’ll be helping the open source community!\n\nHowever without a verified domain there’s no way for any visitors to know that you are who you say you are. To resolve this issue, GitHub recently introduced organization domain verification. The verification process only takes a few minutes, so is definitely worth doing if your organization has an associated domain!\n\nTo complete this tutorial you’ll need Owner permissions for the GitHub organization, and access to your company’s DNS records. Note that completing domain verification will notify all other Owners of the organization. There is also an official GitHub tutorial.\n\nAdding organization email / domain\n\n\n  First, go to your organization’s page.\n  Next, click the “Settings” tab.\n  You can now add a public email and a URL, these must both be verified so use the same domain if possible.\n  Save the changes.\n\n\n\n\nYour URL will now be shown on your organization’s profile, but without the pretty verified tag!\n\nVerifying domain\n\nNow go to the “Verified domains” section on the Settings sidebar. We have to verify that we own the domains we listed on our profile in the earlier step.\n\n\n  Click “Add a domain”.\n  Enter your URL. Note that www.example.com and example.com are different, so use the raw domain (example.com).\n  You’ll be taken to a page with information on the DNS record you need to add. The verification code is unique and expires in 7 days.\n\n\n\n\nNote that the TXT record format is: _github-challenge-&lt;your organization name&gt;.&lt;your domain&gt;.\n\nAdding DNS record\n\nNext, in a new tab you need to go to whoever handles your DNS, in my case Cloudflare. Under the DNS tab, add the TXT record from the previous step.\n\n\n\nNote that once the TXT domain is added your domain suffix will disappear, this is normal!\n\n\n\nVerifying\n\nGo back to your GitHub domain verification tab (or renavigate to it), and click the “Verify” button. Whilst DNS propagation can take up to 72 hours, with a service like Cloudflare this is almost instant.\n\nCongratulations, your domain is now verified! Developers using your libraries are now certain that they are yours.\n\nIn addition to the verified tag, you can now view your member’s email addresses (so long as they are at your domain). For example, if a user has multiple emails registered, and one of them is at your domain, you’ll now be able to see that email!\n\nNote that all members with “Owner” role are emailed to notify them of this change:\n\n\n"
    } ,
  
    {
      "tags"     : "Live, Podcast, Soundcloud",
      "title"    : "Beginner's Guide to Android Development live Q&A podcast recording",
      "excerpt"  : "A couple of months ago the guys at Enhance.co hopped on the Android Dev Discord and took a few questions from the members there. After a few delays this 90 minute podcast is now up on Soundcloud, and embedded below!\n",
      "url"      : "/beginners-guide-to-android-development-live-qa-podcast-recording/",
      "date"     : "Dec 20, 2018",
      "content"  : "A couple of months ago the guys at Enhance.co hopped on the Android Dev Discord and took a few questions from the members there. After a few delays this 90 minute podcast is now up on Soundcloud, and embedded below!\n\nThe podcast covered topics from game engines and Flutter to app publishers and testing, many thanks to the hosts!\n\n\nThis was also posted on /r/androiddev if you’d like to discuss it with other listeners.\n"
    } ,
  
    {
      "tags"     : "Importer, PHP, Plugins, Wordpress",
      "title"    : "How to fix \"Remote file is incorrect size\" WordPress error",
      "excerpt"  : "Whilst trying to RAMP posts from your staging environment to live, or import posts using WordPress Importer, a lot of under-the-hood code has to be run. One of the safety checks included in this is comparing the expected size of files with the actual size. Whilst this usually passes without any issues, occasionally it can cause the transfer to fail, leading to the “Remote file is incorrect size” error.\n",
      "url"      : "/how-to-fix-remote-file-is-incorrect-size-wordpress-error/",
      "date"     : "Dec 19, 2018",
      "content"  : "Whilst trying to RAMP posts from your staging environment to live, or import posts using WordPress Importer, a lot of under-the-hood code has to be run. One of the safety checks included in this is comparing the expected size of files with the actual size. Whilst this usually passes without any issues, occasionally it can cause the transfer to fail, leading to the “Remote file is incorrect size” error.\n\nThis error is occasionally caused by a corrupted file or network issues, but in those cases trying again resolves the issue. If a retry doesn’t fix it, more drastic action has to be taken! Removing the error handling code is an extreme step, so should only be taken if nothing else fixes the issue. That being said, it does instantly solve the problem with no noticeable side effects.\n\n\n\nFind your file size checker\n\nFirst, we need to open the file that performs the size check inside a text editor (e.g. Notepad++).\n\nIf you are using WordPress Importer, this code is in:\n\n/wp-content/plugins/wordpress-importer/wordpress-importer.php\n\n\nIf you are using RAMP, this code is in the following file (on the server being RAMPed to):\n\n/wp-content/plugins/ramp/classes/deploy.class.php\n\n\nComment out the code\n\nNext, comment out the lines that handle file size checking. Do this by adding /* at the start and */ at the end.\n\nIf you are using WordPress Importer, the code to comment out is:\n\nif ( isset( $headers['content-length'] ) &amp;&amp; $filesize != $headers['content-length'] ) {\n\t@unlink( $upload['file'] );\n\treturn new WP_Error( 'import_file_error', __('Remote file is incorrect size', 'wordpress-importer') );\n}\n\n\nIf you are using RAMP, the code to comment out is:\n\n$received_size = filesize($upload['file']);\nif ( $file_size !== $received_size ) {\n\t@unlink($upload['file']);\n\treturn new WP_Error( 'import_file_error', sprintf(__('Remote file is incorrect size: expected %1$d, got %2$d', 'wordpress-importer'), $file_size, $received_size));\n}\n\n\nFinishing up\n\nFinally save your file, push it to your server, then try the importer / RAMP action again. Problem solved!\n\n\n\nThanks to Codeboxr’s Sabuj Kundu’s article for the WordPress Importer addition.\n"
    } ,
  
    {
      "tags"     : "Androidx, Fileprovider, Sharing",
      "title"    : "Sharing internal / cache images (with text) to other Android apps",
      "excerpt"  : "Often, users of your app will want to share images from it. Whether this is their own content, their friend’s content, or content published by you to your users, sharing can massively help your app’s popularity. This can be a little tricky if you’re displaying images from inside your app’s directory, since these files aren’t accessible from other apps! This means that when a user tries to share the image, the app it is shared to will be unable to access it.\n",
      "url"      : "/sharing-internal-cache-images-with-text-to-other-android-apps/",
      "date"     : "Dec 17, 2018",
      "content"  : "Often, users of your app will want to share images from it. Whether this is their own content, their friend’s content, or content published by you to your users, sharing can massively help your app’s popularity. This can be a little tricky if you’re displaying images from inside your app’s directory, since these files aren’t accessible from other apps! This means that when a user tries to share the image, the app it is shared to will be unable to access it.\n\nThe solution to this is creating a FileProvider that makes your images’ directory accessible. Then, forming an intent that grants the app that was shared to permission to view the image.\n\nThe code used in this tutorial was used to add image sharing to my upcoming Astronomy Picture of the Day app. All code used is also available as a GitHub Gist, if you just want to skip to copy and pasting code!\n\nConfiguring file paths XML\n\nFirst, a file needs to be created to define which internal files should be shared. The XML below should be saved as filepaths.xml inside /res/xml/, and makes the /cache/images/ directory available:\n\n&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;paths&gt;\n    &lt;cache-path name=\"shared_images\" path=\"/images/\"/&gt;\n&lt;/paths&gt;\n\n\nNote that if you are using .filesDir and not .cacheDir in your sharing code, &lt;files-path must be used instead of &lt;cache-path.\n\nAdding FileProvider to manifest\n\nThe FileProvider library needs to be added to your project. If you are using AndroidX, it is included already. If you are not, make sure to add the following dependency to your app-level build.gradle:\n\ncompile 'com.android.support:support-v4:28.0.0'\n\n\nNow that our directory to share has been defined, it has to be added to the AndroidManifest.xml, inside the &lt;application&gt; tag. Note that this example uses AndroidX, for non-AndroidX projects the name should be set to android.support.v4.content.FileProvider instead.\n\n&lt;provider\n    android:name=\"androidx.core.content.FileProvider\"\n    android:authorities=\"${applicationId}.fileprovider\"\n    android:grantUriPermissions=\"true\"\n    android:exported=\"false\"&gt;\n    &lt;meta-data\n        android:name=\"android.support.FILE_PROVIDER_PATHS\"\n        android:resource=\"@xml/filepaths\" /&gt;\n&lt;/provider&gt;\n\n\nAdding image sharing function\n\nTo actually share the image, first the file’s URI is retrieved using the previously defined authority and getUriForFile. Next, an intent is created with the following parameters set:\n\n\n  setAction: Determines the intent is for sending content.\n  addFlags: Gives the receiving app permission to view the attached image.\n  setDataAndType: This set the image’s URI, as well as the filetype (e.g. PNG / JPG).\n  putExtra(Intent.EXTRA_STREAM: This adds the URI as a streamable data source.\n  putExtra(Intent.EXTRA_TEXT: This sets the text to be shared alongside the image (where supported).\n\n\nThis intent is then passed to Intent.createChooser, along with a string which may be shown (depending on device).\n\nfun shareImage(file: File) {\n    val authority = \"${BuildConfig.APPLICATION_ID}.fileprovider\"\n    FileProvider.getUriForFile(context, authority, file)?.let {\n        val shareIntent = Intent()\n            .setAction(Intent.ACTION_SEND)\n            .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)\n            .setDataAndType(it, context.contentResolver.getType(it))\n            .putExtra(Intent.EXTRA_STREAM, it)\n            .putExtra(Intent.EXTRA_TEXT, \"I'm sharing this image!\")\n        context.startActivity(Intent.createChooser(shareIntent, \"Share image to:\"))\n    }\n}\n\n\nSharing the image\n\nTo share your image, all you need is a File object of it to be passed to the shareImage function. This can be done using the File(directory, child) constructor:\n\nval imageCache = File(context.cacheDir, \"images\")\nshareImage(File(imageCache, \"myimage.png\"))\n\n\nNote that I’m using the cache directory in this example, .filesDir can be used instead (make sure to change your filepaths.xml too!).\n\nWhen your image sharing function is called, the user will receive a popup suggesting many, many locations to share their content to. A screenshot from newly created emulator is below, real devices will have many pages of options instead!\n\nAll code in this tutorial is available as a Gist.\n\n\n"
    } ,
  
    {
      "tags"     : "Amazon, Calibre, eBooks, Kindle",
      "title"    : "Converting non-Amazon eBooks and sending them to your Kindle using Calibre",
      "excerpt"  : "eBooks are an ever-expanding alternative to traditional books, with a lot of benefits. Since getting a Kindle a couple of years ago, I use it for all eBooks that aren’t picture heavy! Whilst some of these books are from Amazon, so are downloaded automatically to my Kindle, some are from other sources and need converting &amp; sending.\n",
      "url"      : "/converting-non-amazon-ebooks-and-sending-them-to-your-kindle-using-calibre/",
      "date"     : "Dec 11, 2018",
      "content"  : "eBooks are an ever-expanding alternative to traditional books, with a lot of benefits. Since getting a Kindle a couple of years ago, I use it for all eBooks that aren’t picture heavy! Whilst some of these books are from Amazon, so are downloaded automatically to my Kindle, some are from other sources and need converting &amp; sending.\n\nIn this tutorial we’ll set up your Kindle email, then set up Calibre to convert your eBooks and then send them to your Kindle!\n\nCalibre is an ebook management program that is perfect for converting all kinds of eBooks into the few formats Amazon support. Whilst it has a massive list of functions, we’ll only be using the basics in this tutorial. Oh, and if you need a legal source of free eBooks, check out Project Gutenberg and Centsless Books!\n\nSetting up your Kindle email addresses\n\nThe first step is getting an email address to email your eBooks to, this was created when you registered your Kindle with Amazon. Emailing this address (with your eBooks as attachments) will automatically send the book to your Kindle:\n\n\n  First, go to the “Preferences” tab of “Managed Your Content and Devices” (change .com to your country’s Amazon if necessary, e.g. .co.uk!).\n  Scroll down to “Personal Document Settings”, and click the title or description.\n  Under “Send-to-Kindle E-mail Settings”, you should see your Kindle listed, as well as an email address. Make a note of this email for later (you can also change it if you wish).\n\n\nNext, we need to set up an email that we are allowed to send ebooks from, we don’t want anyone to be able to put stuff on our Kindle!\n\nThis is done by scrolling down a little bit to “Approved Personal Document E-mail List”, and adding your own email address to the list. You can also add an entire domain, which is very useful if you use multiple emails (e.g. I use many different emails, all at @jakelee.co.uk).\n\n\n\nSetting up Calibre\n\nCalibre is an extremely powerful eBook management tool, but we’re only going to be using the eBook conversion &amp; emailing functionality. There is a comprehensive beginner’s guide by the creator himself embedded below, but viewing it is not essential for this tutorial!\n\n\n\nInstalling Calibre\n\n\n  Download Calibre here, by selecting your operating system and pressing “Download calibre”.\n  Install the application like any other, accepting Terms of Service etc.\n  Open Calibre.\n\n\nConfiguring your Kindle\n\nWhen Calibre starts for the first time, it will run the Welcome Wizard to help set up your installation. During this, various questions will be asked:\n\n\n  Book location: The default location (Documents -&gt; Calibre Library) is fine for this.\n  eReader: Select Amazon, then your Kindle model.\n  Kindle email: Enter the email address retrieved earlier from “Send-to-Kindle E-mail Settings”.\n  Send email from: Enter your personal email address added to the “Approved Personal Document E-mail List” earlier.\n  Click “Test email”.\n  A few minutes later, you should receive an email in your inbox from Amazon, saying your email didn’t contain any eBooks. It works!\n\n\n\n  \n    \n      Setup\n      Email\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nConfiguring file conversion\n\nNext, we need to make sure Calibre outputs the files in a format appropriate for emailing to Kindle. To do this:\n\n\n  Click “Preferences” at the top.\n  Click “Sharing books by email” under “Sharing”.\n  Make sure your Kindle’s email is listed there, with “Formats” set to “MOBI”. If it is set to anything else, double click to change it to “MOBI”.\n  Apply these changes.\n\n\n\n\nYou’re all set up! Now it’s time to actually try sending an eBook…\n\nUsing Calibre to convert and send eBooks\n\n\n  Get an eBook. This can be a .pdf, .epub, .txt, .doc, .mobi, pretty much anything will work! Free, legal eBooks can be downloaded from Project Gutenberg if you need inspiration.\n  Click “Add books” on Calibre.\n  Pick your eBook file from your file system.\n  Calibre should now show all the metadata about your book (title, author, publication date, etc). This can be changed by clicking “Edit metadata” at the top.\n\n\n\n\n\n  Right click your book, select “Connect/Share”, and choose “Email to youremail@kindle.com”.\n  You should now see “Jobs: 1” or “Jobs: 2” in the bottom right of Calibre. This can be clicked for more information, but once it says “Jobs: 0” your eBook has been sent!\n  Your eBook will sync eventually if your Kindle has internet, but you can force it to sync immediately. For example, from a Paperwhite:\n    \n      Return to the library view.\n      Select the sun / gear icon at the top.\n      Tap “Sync My Kindle”.\n    \n  \n  Your eBook is now on your device!\n\n\n\n\nIf you encounter any problems, feel free to leave a comment and I’ll do my best to help!\n"
    } ,
  
    {
      "tags"     : "Chrome, Extension, History, JavaScript, Plugin",
      "title"    : "Creating a history clearing Chrome extension",
      "excerpt"  : "Chrome extensions are small plugins that modify how Chrome (or websites viewed in it) look and behave. These can notify you of events (e.g. Google Mail Checker or Inoreader Companion), modify sites (e.g. Reddit Enhancement Suite or uBlock Origin), or add functionality (e.g. HTTPS Everywhere).\n",
      "url"      : "/creating-a-history-clearing-chrome-extension/",
      "date"     : "Dec 9, 2018",
      "content"  : "Chrome extensions are small plugins that modify how Chrome (or websites viewed in it) look and behave. These can notify you of events (e.g. Google Mail Checker or Inoreader Companion), modify sites (e.g. Reddit Enhancement Suite or uBlock Origin), or add functionality (e.g. HTTPS Everywhere).\n\nA couple of years ago, I made a very simple Chrome extension called Selective Scrubber that removed predefined domains &amp; terms from your Chrome history. This tutorial will cover the code behind it, as well as how to upload an extension like this.\n\nBefore diving into this project, I strongly recommend looking at the final result, and checking out the extension’s repository. It’s also worth noting that this extension doesn’t work if using Chrome history sync, due to a long-standing bug (4 years!).\n\nCreating extension framework\n\nTo start, we’re going to use the simplest extension possible, a project folder containing a file called manifest.json. Add the following into the file:\n\n{\n    \"name\": \"My extension\",\n    \"version\": \"1.0.0\",\n    \"description\": \"My extension doesn't do anything yet!\",\n    \"manifest_version\": 2\n}\n\n\nTechnically you’ve now created an extension, congratulations! There’s a bit more work to do for it to be actually useful however…\n\nPreparing Chrome for extension development\n\nBefore any extension code can be run, running local unpacked extensions must be enabled. This is done by navigating to your extensions page (chrome://extensions/), and:\n\n\n  Toggling “Developer mode” to on in the top right.\n  Selecting the newly visible “Load unpacked” option.\n  Selecting your project folder.\n\n\nYour extension should now be visible in your extensions list! The little “Reload” icon must be clicked after every time you make code changes to make Chrome run the updated code.\n\n\n\nPreparing the manifest\n\nFirst, add the following snippet to your manifest.json file, to tell Chrome that we’re going to be using a background JavaScript file:\n\n\"background\": {\n    \"persistent\": false,\n    \"scripts\": [\"js/clear_history.js\"]\n},\n\n\nNext, create a folder called js and add clear_history.js into it. This can be left empty for now.\n\nWe’re also going to have an options page, so that must be registered in the manifest.json too:\n\n\"options_ui\": {\n    \"page\": \"options.html\",\n    \"chrome_style\": true\n}\n\n\nAgain, create the options.html page in the project folder. After reloading the extension (with the reload button on the extension’s card), you should now see a “Inspect views background page” link. Clicking this won’t do anything, but it’s presence confirms your background script earlier has been registered successfully!\n\n\n\nWe’re also going to need permissions for storage (for preferences) and history (for deleting entries), so add the following into the manifest too:\n\n\"permissions\": [\"history\", \"storage\"],\n\n\nAdding toolbar icon\n\nNext, we’re going to add a toolbar icon for our extension, so that we can see it is installed and access the options. To do this, we need an app icon in both 48×48 and 96×96 sizes. I’d recommend using Google’s Material Design icon library, and exporting PNG icons in 48dp (this provides both the necessary app sizes). For this tutorial, I’ll use the find_replace icon.\n\n\n\nOnce you’ve got your icons, rename them to icon_48.png and icon_96.png, then place them inside an images folder in your project folder. Now that we’ve got image assets, edit the manifest.json to include them as icons (for the extension store), and as a browser_action to appear in the toolbar.\n\n\"icons\": {\n    \"48\": \"images/icon_48.png\",\n    \"96\": \"images/icon_96.png\"\n},\n\"browser_action\": {\n    \"default_icon\": \"images/icon_96.png\"\n},\n\n\nAfter reloading the extension, it will now appear in your Chrome toolbar! Right clicking it shows an “Options” menu, which currently… opens an empty page. Time to fix that!\n\n\n\nCreating the options screen\n\nIn this section, we’ll be creating the Chrome extension’s options, where users can edit their scrub list and toggle a scrub summary message.\n\nOptions HTML\n\nOpen up the options.html file inside the project root. The HTML content is very simple, containing a text area, a checkbox, a button, and a status:\n\n&lt;html&gt;\n    &lt;body&gt;\n        &lt;p&gt;Which sites / phrases should be scrubbed? One per line!&lt;/p&gt;\n        &lt;textarea id=\"sites\" rows=\"4\" cols=\"50\"&gt;&lt;/textarea&gt;&lt;br&gt;&lt;br&gt;\n        &lt;label&gt;&lt;input id=\"popup\" type=\"checkbox\"&gt;Display scrub summary?&lt;/label&gt;&lt;br&gt;&lt;br&gt;\n        &lt;button id=\"save\"&gt;Save&lt;/button&gt; &lt;b id=\"status\" /&gt;\n        &lt;script src=\"js/options.js\"&gt;&lt;/script&gt;\n    &lt;/body&gt;\n&lt;/html&gt;\n\n\nAccessing the options screen will now show our options! However, since there’s no functional code yet, it’s not particularly useful.\n\nCreate the options.js file inside the js folder, this will contain all of the JavaScript for our options page. The options page contains 2 pieces of functionality; saving preferences, and loading preferences.\n\nSaving options\n\nFirst, an event listener must be added to the “Save” button, so that saving happens when it is pressed. Add the following into options.js:\n\ndocument.getElementById('save').addEventListener('click', save);\n\n\nNow we need to create the save function that the listener calls. This function gets the list of sites from the text area and the “Display scrub summary?” checkbox answer, then places them in Chrome storage. Note that displaySavedMessage is the function to be called when data has been successfully saved. This function just displays a piece of text in the status field of the page, then removes it after 2 seconds.\n\nfunction save() {\n    var sitesToSave = document.getElementById('sites').value;\n    var displayPopup = document.getElementById('popup').checked;\n    chrome.storage.sync.set({\n        sites: sitesToSave,\n        popup: displayPopup\n    }, displaySavedMessage);\n}\n\nfunction displaySavedMessage() {\n    var status = document.getElementById('status');\n    status.textContent = 'Sites saved.';\n    setTimeout(function() {\n        status.textContent = '';\n    }, 2000);\n}\n\n\nLoading options\n\nData is now being saved! The next step is to load this data when the options page is opened. This is done using event listeners again:\n\ndocument.addEventListener('DOMContentLoaded', load);\n\n\nAgain, we now need to create the load function. The options are pulled from Chrome storage again, this time with a default site list and popup value. Once options are loaded (default or user-set), the UI is updated accordingly.\n\nfunction load() {\n    chrome.storage.sync.get({\n        sites: 'supersecretsite.com',\n        popup: false\n    }, function(items) {\n        document.getElementById('sites').value = items.sites;\n        document.getElementById('popup').checked = items.popup;\n    });\n}\n\n\nSaving and loading data is now complete! This can be tested by changing your options, saving, then reopening the options page. If everything worked, your changes should have persisted.\n\n\n\nClearing out history when clicked\n\nFor the actual history clearing, we’re going to need to open up the clear_history.js file created at the very start.\n\nFirst, add a listener to the browser button being clicked. When clicked, the options will be loaded, then passed to deleteBySites when ready:\n\nchrome.browserAction.onClicked.addListener(function(tab) {\n    chrome.storage.sync.get({\n        sites: 'supersecretsite.com',\n        popup: false\n    }, deleteBySites);\n});\n\n\ndeleteBySites splits the sites value loaded from Chrome storage, one site per line. numSites is set for later, then for each site deleteBySite is called:\n\nvar numSites = 0;\nfunction deleteBySites(storage) {\n    var allSites = storage.sites.split(\"\\n\");\n    numSites = allSites.length;\n    for (var i = 0; i &lt; allSites.length; i++) {\n        deleteBySite(allSites[i], storage.popup);\n    }\n}\n\n\ndeleteBySite performs a search of Chrome’s history for the specified phrase, which returns a list of results. These results are then iterated over, deleting all, as well as keeping a running tally of the number of results deleted. Finally, if the popup option is true, the results are passed to siteDeleted.\n\nfunction deleteBySite(site, popup) {\n    chrome.history.search({\n            text: site,\n            startTime: 0,\n            maxResults: 999999\n        },\n        function(results) {\n            var itemsDeleted = 0;\n            for (itemsDeleted; itemsDeleted &lt; results.length; itemsDeleted++) {\n                chrome.history.deleteUrl({\n                    url: results[itemsDeleted].url\n                });\n            }\n            if (popup) {\n                siteDeleted(site, itemsDeleted);\n            }\n        });\n}\n\n\nsiteDeleted adds the site and deleted entries count to siteString, then displays a summary if every site has been processed. This is checked by making sure sitesProcessed is equal to (or larger than) the numSites we defined earlier. Finally, this text is shown as a popup alert.\n\nvar sitesProcessed = 0;\nvar siteString = \"Scrub complete:\\n\";\nfunction siteDeleted(site, count) {\n    sitesProcessed++;\n    siteString += (count + \"x \" + site + \"\\n\");\n    if (sitesProcessed &gt;= numSites) {\n        alert(siteString);\n        sitesProcessed = 0;\n        siteString = \"Scrub complete:\\n\";\n    }\n}\n\n\n\n\nThe extension is now fully working! The only thing left to do is prepare it for release, and upload it.\n\nPreparing your Chrome extension for release\n\nYour app’s name and description in your manifest.json should now be changed to something unique. Additionally, you might want to set a `` and a version. Whilst version must be numerical, versionName can be anything you want. Semantic Versioning is a good way of ensuring consistent, understandable version codes.\n\nFinally, right click your extension’s folder, and make a .zip archive of it (“Send to” -&gt; “Compressed (zipped) folder”).\n\nPublishing your Chrome extension\n\n\n  Go to the beta Chrome Developer Dashboard (you may need to opt in).\n  Register as a developer, and pay the necessary $5 registration fee (to prevent spam).\n  Click “New item” in the top right, and select your .zip file.\n  You will then have a draft extension, which needs the following fields to be filled in before publishing:\n    \n      Extension’s language\n      Extension’s primary category\n      1-5 screenshots (1280×800 or 640×400)\n    \n  \n\n\nOnce these 3 fields have been filled in, your extension is ready to publish! However, you’ll likely want to customise the support URLs, app icons, detailed description, and a few other pieces of metadata. When you’re ready to go, press “Publish item” in the top right.\n\nCongratulations, it’s published!\n\n\n\nThis entire project is available as a repository, and the finished extension can be installed here.\n\nAdditional resources:\n\n\n  Simple getting started guide by Google\n  Complete guide to publishing by Google\n\n"
    } ,
  
    {
      "tags"     : "Drive, Gmail, Google, Storage",
      "title"    : "How To Free Up Space in Google Drive, Gmail, and Google Photos",
      "excerpt"  : "I’ve been lightly using Google Drive, Gmail, and Google Photos for close to 6 years, with no major complaints. The default space limitation is 15GB, with an extra 2GB available for each year the security checkup is completed. There was also previously 100GB (expiring after a year) available for local guides, but this program is now cancelled.\n",
      "url"      : "/how-to-free-up-space-in-google-drive-gmail-and-google-photos/",
      "date"     : "Dec 8, 2018",
      "content"  : "I’ve been lightly using Google Drive, Gmail, and Google Photos for close to 6 years, with no major complaints. The default space limitation is 15GB, with an extra 2GB available for each year the security checkup is completed. There was also previously 100GB (expiring after a year) available for local guides, but this program is now cancelled.\n\nRecently I realised I was getting unnervingly close (84%) to my 19GB limit, and went on a quest to minimise this amount as much as possible, eventually getting it down to 6% without losing any useful content!\n\nFirst, view your overall usage at Google One, this will help you guide your efforts to the biggest space hoggers. My initial overview is shown below, further updates will be shown throughout this tutorial.\n\n\n\nDrive\n\nThe biggest user of space was Google Drive, so that seemed a sensible place to start. A three pronged attack would be used; deleting large files, deleting unused files, and emptying the bin.\n\nEmptying Google Drive bin\n\nI have Google Drive synced to a local folder on my PC, so my first step was checking the disk space used.\n\n\n\nIt turned out to be just 1GB, so where on earth was the extra 8.4GB coming from!?\n\nAfter a little research, I discovered every deleted file in Google Drive is kept… forever. That 500MB video you used Google Drive to transfer 5 years ago, then deleted the next day? It’s still there! Those few thousand image assets you downloaded for a project then ended up deleting? Still there!\n\nLuckily, it is possible to empty this bin. Just visit the Trash, then click “Bin” and “Empty bin”. Due to the 6 years of files hidden away in there for me, this process took around half an hour to complete. During that time, the Trash would show a random selection of files, so it was hard to tell if it was actually making any progress. Viewing the storage overview page gives a more up to date account of your space usage. Note that due to the time taken to empty the bin, later screenshots in this tutorial will have ever-decreasing Google Drive sizes!\n\n\n\nCleaning out Google Drive\n\n\n\nFirst, visit the quota page and sort by “Storage used”. This will show you your largest files, and let you delete them. This is useful for any forgotten large files (e.g. videos, 3D renders) that are no longer useful.\n\nHowever, this approach misses any small files, and fails to give you a more general overview of your space used. Luckily, WinDirStat (Windows Directory Statistics) exists, an application which provides a very detailed analysis of the space used in a specific folder.\n\nWhilst WinDirStat definitely isn’t a pretty program, or particularly easy to understand the first time round, it’s worth learning. When run on your Google Drive folder, it will tell you:\n\n\n  Which folders / subfolders are using the most space (top left)\n  Which file types are using the most space (top right)\n  A visual representation of every file, with larger ones appearing larger.\n\n\nClicking on a file’s visual representation will show you the location, filename, and filetype. Using this information, you can delete any large files / collections of files you no longer wish to keep. For example, the screenshot below has a large .psd selected.\n\n\n\nNow that large / unneeded files have been removed and the bin has been emptied, the Google Drive space used is just 30% of the original, a very nice start!\n\n\n\nGmail\n\nAs I use Gmail for all of my daily emails (across at least 5 accounts), there are tens of thousands of emails that have been archived forever and forgotten about. Whilst Gmail only uses 1.35GB, that seemed pretty excessive considering I’m not intentionally keeping any files / emails!\n\nLarge files\n\nThe first task is removing any large attachments that are hidden away in old emails. Luckily, Gmail has extremely powerful search operators that can be used to filter emails. For this task we want to delete emails with attachments, that are at least 20MB in size. To do this, enter the following into the Gmail search bar:\n\nhas:attachment size:20MB\n\n\nYou can of course change 20MB to 10MB or any other amount, depending on how aggressively you want to free up space.\n\nJunk emails\n\nNext, I noticed that there were thousands and thousands of emails that had already been actioned, or were just notifications in email form. Whilst there were around 4,000 unread emails like this, there were at least 25,000 already read!\n\nLuckily, Gmail automatically categorises most emails into “Social”, “Updated”, “Forums”, or “Promotions”. Clearing these out was just a case of:\n\n\n  Going to each folder\n  Clicking the “Select all” square at the top\n  Clicking the “Select all X messages in Y” bar at the top\n  Pressing the trash icon\n\n\n\n  \n    \n      Folders\n      Select all\n      Category\n    \n  \n  \n    \n      \n      \n      \n    \n  \n\n\nDeleting thousands of emails can take a few seconds, make sure not to close the tab before it is done! The space used by Gmail has now dropped from 1.35GB to 0.41GB, without anything important being lost. Note that Google Drive’s space is still slowly going down, as it works through the thousands of deleted files from the previous step!\n\n\nGoogle Photos\n\nThe final section to clear out is Google Photos. For this, I used Google Photos’ unlimited “High Quality” storage option. With this option, your full quality photos are replaced with “high” quality ones, which don’t count towards your allocation. High quality is defined as a maximum of 16MP, which is good enough for everyday usage (especially with my poor photography skills!).\n\n\n\n\nTo apply this setting, visit your Google Photos settings and change the “Upload size” setting from “Original” to “High quality”. This process takes around 5 minutes per 500MB, and is a good way of freeing up a large amount of space for very little effort.\n\n\n\nThe space used by Google Photos has now dropped from 5.32GB to 0GB. Pretty good!\n\nConclusion\n\n\n  \n    \n      Before\n      After\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nSo, the total space used has dropped from 16.07GB to 1.14GB, and from 84% utilisation to just 6%. Plenty of space now!\n\nEmptying the Google Drive trash was by far the biggest space saving action, freeing up around 8GB of space. Whilst I have relied on Google Drive’s trash in the past, it’s surprising that it can grow to be 8x the size of the actual files, and not have any automatic emptying. Gmail’s trash folder is emptied after 30 days naturally.\n\nIf these space freeing techniques don’t free up enough space, there are paid plans available. The prices are very reasonable, with plans ranging from 100GB (£1.59/mo) to 30TB (£239.99/mo). Dropbox only offers a single 2TB paid plan, whilst OneDrive offer 3 premium plans, all more expensive than comparable Google One plans. As well as having very competitive pricing, the main advantages of Google’s plans are their integration into services you’re likely using already (Google Photos, Gmail, Google Drive).\n"
    } ,
  
    {
      "tags"     : "Firebase, Kotlin, Performance, Tutorial",
      "title"    : "Ensuring Your Android App's Quality With Firebase Performance Monitoring",
      "excerpt"  : "Firebase Performance Monitoring allows you to gather automatic performance data about your app, as well as performing manual performance traces for later analysis. All of these contain aggregated information about user’s devices, meaning long-term issues can be quickly identified and resolved.\n",
      "url"      : "/ensuring-your-android-apps-quality-with-firebase-performance-monitoring/",
      "date"     : "Dec 6, 2018",
      "content"  : "Firebase Performance Monitoring allows you to gather automatic performance data about your app, as well as performing manual performance traces for later analysis. All of these contain aggregated information about user’s devices, meaning long-term issues can be quickly identified and resolved.\n\nThis post is part of The Complete Guide to Firebase. Throughout this tutorial, you’ll need access to the Firebase Performance Monitoring dashboard, and the official documentation may be useful.\n\nImplementation\n\nAs always, the entire Firebase Reference Project is open source, and there is a pull request for adding Firebase Performance Monitoring if you just want to see the code changes required. This tutorial assumes you already have Firebase added to your project.\n\nIn this tutorial, you’ll learn how to monitor the performance of your app, as well as benchmark specific scenarios across all users. You’ll also be able to track network requests, startup time, and how long your app was in the foreground.\n\nAdding Performance Monitoring to your project\n\nFirst, in your app-level build.gradle, just below apply plugin: 'com.android.application' add:\n\napply plugin: 'com.google.firebase.firebase-perf'\n\n\nStill in the same file, add implementation 'com.google.firebase:firebase-perf:16.2.0' to your dependencies.\n\nNext, in your project-level build.gradle, in the buildscript -&gt; repositories section, make sure jcenter() is listed.\n\nFinally, still in the same file, add the following inside buildscript -&gt; repositories:\n\nclasspath 'com.google.firebase:firebase-plugins:1.1.5'\n\n\nPerform a Gradle Sync, and your app’s performance + network requests are now being monitored!\n\nPerforming manual traces\n\nWhilst app startup time, activity time, app background, and app foreground times are all measured automatically, you may wish to add your own time tracking.\n\nThis can be done in 2 ways:\n\nFirst, specifying methods to always track via annotations. This is useful if you want to measure entire methods, don’t want to track custom metrics, and want to keep your actual functions short and clean. This is done by adding @AddTrace(name = \"yourTraceName\") before a method. For example, this function’s time is tracked under the trace name “automatic”:\n\n@AddTrace(name = \"automatic\")\nprivate fun performAutomaticTrace() {\n    for (i in 1..(1..20).shuffled().last()) {\n        Log.d(\"Performance\", \"Value is $i\")\n        sleep(100)\n    }\n}\n\n\nThe second method is manually starting a trace. This is used when you wish to modify the trace’s metadata whilst it is running, such as modifying custom attributes being tracked. These manual traces are started by creating a trace using FirebasePerformance.getInstance().newTrace(\"yourTraceName\"), then starting it with .start(). The trace can then be stopped with .stop(). For example, this function’s time is tracked under the trace name “manual”:\n\nprivate fun performManualTrace() {\n    val trace = FirebasePerformance.getInstance().newTrace(\"manual\")\n    trace.start()\n    for (i in 1..(1..10).shuffled().last()) {\n        sleep(100)\n    }\n    trace.stop()\n}\n\n\nMonitor custom attributes\n\nIn addition to monitoring overall performance, you can also set and modify up to 5 custom attributes per trace. This can be useful for logging which code version an A/B tester is on. It can also be useful if you want to track how many times a user performs a specific action during the trace.\n\nYou must use the second method listed above (.newTrace()) to use custom attributes, as you need a reference to a trace. Once you have your reference, you can set a value using putAttribute(name, value):\n\ntrace.putAttribute(\"run_manual\", true.toString())\n\n\nThis value can also be retrieved with trace.getAttribute(name) and removed with trace.removeAttribute(name).\n\nNote that attributes are always stored as strings. However, if you wish to store numerical values you can use trace.incrementMetric(name, amount). This value can be retrieved with trace.getLongMetric(name), but cannot be deleted.\n\nWeb interface\n\nDashboard\n\nThe dashboard provides an overview of any emerging issues that require attention, as well as any poorly performing screens and other important metrics.\n\n\n  \n    \n      Issue list\n      More\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nClicking an issue will provide more information about it (similar to Crashlytics), as well as the option to close or mute the issue.\n\nOn device\n\nThe on device tab provides an overview of trace durations, both manual and automatic. Clicking any will provide a more detailed overview, as well as the option to view extremely detailed data for a specific session. This data is extremely useful when diagnosing issues like a memory leak or sluggish performance.\n\n\n  \n    \n      Sessions\n      More sessions\n    \n    \n      \n      \n    \n  \n\n\nNetwork\n\n\n\nThis tab shows information about network requests included in your traces, and is covered in detail in the official Firebase docs.\n\nConclusion\n\nWhilst there is a slight risk of a performance overhead being added (somewhat ironically) when performing traces, this is usually outweighed by the benefits gained from knowing exactly how your app is performing. For example, if the median app start time has doubled after an update, without Firebase Performance Monitoring there wouldn’t be any way to know this! You could then track individual session and identify exactly what has changed since an earlier version.\n\nNote that there are a few limitations with this method of performance monitoring. Most notably, only the main process can be monitored, meaning apps that make heavy use of threads or RxJava may end up with inaccurate reporting. Despite this, the service is free for unlimited usage, so is definitely worth including from the start on all apps. The collected data is then useful when attempting to optimise performance at a later date.\n\nPrevious: Ensuring Your Android App’s Quality With Firebase Crashlytics\n\nThanks to Firebase docs for some of the images used in this article.\n"
    } ,
  
    {
      "tags"     : "Discord",
      "title"    : "Android Development Discord Communities",
      "excerpt"  : "Whilst developing for Android, it’s often necessary to ask others for help, or discuss concepts / news. Whilst StackOverflow is excellent for solving problems long-term, sometimes it’s easier to talk through something in realtime. To that end, Discord is an excellent resource, this post will introduce a few of the larger communities.\n",
      "url"      : "/android-development-discord-communities/",
      "date"     : "Dec 3, 2018",
      "content"  : "Whilst developing for Android, it’s often necessary to ask others for help, or discuss concepts / news. Whilst StackOverflow is excellent for solving problems long-term, sometimes it’s easier to talk through something in realtime. To that end, Discord is an excellent resource, this post will introduce a few of the larger communities.\n\nI currently help moderate all of these communities, so feel free to message me on Discord (@JakeSteam#9845) with any questions!\n\nAndroid Development Servers\n\nAndroid Dev: This is the main Android development server. With over 3,000 members, the #beginner and #intermediate rooms have helpful people available 24/7. There are also specialist rooms to discuss libraries like #firebase and #dagger, and lots of information in #useful-resources. Finally, there is also #promotion, #app-showcase, and #hiring to promote various types of content.\n\n\n\nFlutter Dev: Whilst smaller than the main server (1.6k members), the specialised nature of the server (Google’s Flutter framework) means it is much more helpful than the #flutter channel of Android Dev. As it is part of the same server network as Android Dev (Devs on Discord), they share the same channel structure.\n\n\n\nGeneral Android Servers\n\n/r/Android: This massive server (12k users) is loosely affiliated with the subreddit, but has a very different tone. With very relaxed rules, most of the conversation ends up happening in #offtopic.\n\n\n\n/r/AndroidGaming: This server (1.4k members) focuses on gaming news and discussion, as well as game recommendations and sharing content. Special roles are available for YouTubers, Twitch streamers, and game developers.\n\n\n\n/r/AndroidQuestions: This server is quieter than the others (500 members), and is full of people asking questions, and a few helping. Generally the subreddit is a better place to ask, but it can’t hurt asking here too.\n\n\n"
    } ,
  
    {
      "tags"     : "Firebase, Heartbeat, Scheduling",
      "title"    : "Scheduling A Repeating Background Task On Android, With Power / Internet Requirements",
      "excerpt"  : "Whilst developing Android apps, performing a scheduled task at set intervals is a very common requirement. Despite this, there are a surprisingly high number of solutions, each with their own advantages and disadvantages. This tutorial will focus on using Firebase JobDispatcher, a library that uses Google Play services to provide a backwards compatible (API 14+) job scheduling library. This makes it an attractive option for those that need to support older devices, and know their users will have Google Play installed:\n",
      "url"      : "/scheduling-a-repeating-background-task-on-android-with-power-internet-requirements/",
      "date"     : "Dec 3, 2018",
      "content"  : "Whilst developing Android apps, performing a scheduled task at set intervals is a very common requirement. Despite this, there are a surprisingly high number of solutions, each with their own advantages and disadvantages. This tutorial will focus on using Firebase JobDispatcher, a library that uses Google Play services to provide a backwards compatible (API 14+) job scheduling library. This makes it an attractive option for those that need to support older devices, and know their users will have Google Play installed:\n\n\n\nThis tutorial will walk you through the simple steps needed to implement Firebase JobDispatcher, as well as the customisation options available. A minimal example project of this tutorial’s implementation is available as a repository, or as a Gist. Kotlin is used, but all code is straightforward and can be converted to Java.\n\nChecking scheduled jobs\n\nThroughout this tutorial, the ability to check the currently scheduled tasks / jobs is extremely useful. As there is no GUI for this, it must be done by running the following in the “Terminal” tab of Android Studio (replacing uk.co.jakelee.scheduledjobs with your app’s package name):\n\nadb shell dumpsys activity service GcmService --endpoints uk.co.jakelee.scheduledjobs\n\n\nThis will return a lot of information, most of it not useful (e.g. every saved WiFi network!). The first of the important parts is the task count, showing the number of registered jobs:\n\n\n\nThe second is the pending &amp; past executions list. This shows your tasks, their internet / scheduling requirements, and their execution history:\n\nPending:\n(scheduled) uk.co.jakelee.scheduledjobs/com.firebase.jobdispatcher.GooglePlayReceiver{u=0 tag=\"uk.co.jakelee.scheduledjobs.job\" trigger=window{start=15s,end=30s,earliest=-369s,latest=-354s} requirements=[NET_ANY] attributes=[RECURRING] scheduled=-384s last_r\nun=N/A jid=N/A status=PENDING retries=0 client_lib=FIREBASE_JOB_DISPATCHER-1}\nNot yet run.\n\nPast executions:\n[cost:100%] (finished) [uk.co.jakelee.scheduledjobs/com.firebase.jobdispatcher.GooglePlayReceiver:uk.co.jakelee.scheduledjobs.job,u0]\nsuccesses: 60 reschedules: 0 failures: 0 timeouts: 0 invalid_service: 0 total_elapsed_millis: 2842 total_uptime_millis: 2848\n\n\n[NET_ANY] shows that any internet connection type is acceptable, [RECURRING] shows that I’ve set it to repeat, window{start=15s,end=30s ... } shows that I’ve scheduled it to repeat very frequently.\n\nAdding Firebase JobDispatcher library\n\nFirst, add the Firebase JobDispatcher library to your app-level build.gradle:\n\nimplementation 'com.firebase:firebase-jobdispatcher:0.8.5'\n\n\nNext, add a service for the JobScheduler to your AndroidManifest.xml. The .JobScheduler doesn’t exist yet, but you’ll be making it in the next step!\n\n&lt;service\n    android:name=\".JobScheduler\"\n    android:exported=\"false\"&gt;\n    &lt;intent-filter&gt;\n        &lt;action android:name=\"com.firebase.jobdispatcher.ACTION_EXECUTE\" /&gt;\n    &lt;/intent-filter&gt;\n&lt;/service&gt;\n\n\nCreate JobScheduler class\n\nJobScheduler.kt is the class that handles the actual scheduling. The rest of this tutorial will describe the implementation process, but there is also a Gist of the implementation.\n\nFirst, create the class, making sure to extend JobDispatcher’s JobService:\n\nclass JobScheduler : JobService() {\n\n\nNext, create a companion object with a tag for your job, so you can identify it later:\n\ncompanion object {\n    private const val SIMPLE_JOB_TAG = \"uk.co.jakelee.scheduledjobs.job\"\n}\n\n\nWhen a scheduled task starts, onStartJob is called. This method is overridden to trigger the intended job. We’ll cover setting the tag later, but for now just check it has been correctly set and pass the JobParameters object to simpleJob. Note that this method returns a boolean determining whether it has more work to do. This should almost always be false.\n\noverride fun onStartJob(job: JobParameters): Boolean {\n    Log.d(\"JobScheduler\", \"Job started\")\n    when (job.tag) {\n        SIMPLE_JOB_TAG -&gt; simpleJob(job)\n        else -&gt; return false\n    }\n    return true\n}\n\n\nNext up is actually creating the job function. This can do anything you want (that doesn’t require an activity), in this example it just writes a line to the log and finishes the job. Note that jobFinished needs to be passed the JobParameters object initially passed to onStartJob, as well as a boolean for whether the task needs to be retried (usually false).\n\nprivate fun simpleJob(job: JobParameters) {\n    Log.d(\"JobScheduler\", \"Ran job ${job.tag}\")\n    jobFinished(job, false)\n}\n\n\nFinally, onStopJob must be overridden. Just like onStartJob, this also has to return a boolean, this time determining whether to retry the job (usually true). onStopJob is called when your job stops during execution, usually because it is taking too long to complete. The normal maximum execution time is 10 minutes, but this can vary, so try to complete your task much quicker than the limit.\n\noverride fun onStopJob(job: JobParameters?) = true\n\n\nScheduling a job\n\nScheduling a recurring job is luckily very simple, and has a lot of customisable options:\n\nfun scheduleJob(context: Context) {\n    val dispatcher = FirebaseJobDispatcher(GooglePlayDriver(context))\n    val exampleJob = dispatcher.newJobBuilder()\n        .setService(JobScheduler::class.java)\n        .setTag(SIMPLE_JOB_TAG)\n        .setRecurring(true)\n        .setLifetime(Lifetime.FOREVER)\n        .setReplaceCurrent(true)\n        .setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)\n        .setConstraints(Constraint.ON_UNMETERED_NETWORK, Constraint.DEVICE_CHARGING)\n        .setTrigger(Trigger.executionWindow(5, 10))\n    dispatcher.mustSchedule(exampleJob.build())\n    Log.d(\"JobScheduler\", \"Scheduled job\")\n}\n\n\nIn this example, the following parameters apply:\n\n\n  setService determines the class called when this job triggers. This is sometimes another class, but it’s often easier to trigger the same class as the scheduling occurs in.\n  setTag sets the job’s tag, used when the job starts to check which job it is.\n  setRecurring sets whether a job should repeat or not.\n  setLifetime determines if the job scheduling should last UNTIL_NEXT_BOOT or FOREVER.\n  setReplaceCurrent decides if this job should replace existing tasks with the same tag, or leave them.\n  setRetryStrategy lets you set custom retry strategies if a job fails, or use the built-in EXPONENTIAL / LINEAR.\n  setConstraints allows you to set requirements for the job to run. This is used to only allow the task to run on an unmetered network (e.g. WiFi) whilst charging.\n  setTrigger lets you either execute a job now (JobTrigger.NOW) or schedule the task. The 2 numbers are the earliest and latest times (since last execution or job scheduling) that the job should be executed. In this example, the task should be run every 5-10 seconds.\n\n\nCancelling a job\n\nOnce you have a JobDispatcher instance with FirebaseJobDispatcher(GooglePlayDriver(context)), you can either unschedule all jobs (.cancelAll()), or unschedule individually (.cancel(tag)).\n\nConclusion\n\nFirebase’s JobDispatcher library provides a simple way to schedule future tasks. I recently used this approach to implement an app “heartbeat”, where it sends a small message to a server every 24 hours. The time of the heartbeat was very flexible, so a large window of activation is provided (20-28 hours). Having this window (in setTrigger()) as large as possible helps reduce your app’s battery usage, as it allows the device to stay in Doze mode for as long as possible.\n\nThe only downside is the requirement on Google Play Services to centrally coordinate your job scheduling. If you distribute your app via the Play Store this isn’t an issue, but will cause serious problems for those distributing externally.\n\nNote that this is just one of the many services Firebase offers, and there is an ongoing series covering each one.\n"
    } ,
  
    {
      "tags"     : "Firebase, Invites, Kotlin, Sharing",
      "title"    : "Growing Your Android App With Firebase Invites",
      "excerpt"  : "Firebase Invites provide a simple way to add user referral schemes to your app for free, without any additional resources. The system runs on top of Firebase Dynamic Links, and supports both email and SMS referrals.\n",
      "url"      : "/growing-your-android-app-with-firebase-invites/",
      "date"     : "Nov 28, 2018",
      "content"  : "Firebase Invites provide a simple way to add user referral schemes to your app for free, without any additional resources. The system runs on top of Firebase Dynamic Links, and supports both email and SMS referrals.\n\nInvite messages can be customised, and they can include custom data / deep links. This custom information works even if the user doesn’t have the app installed when they initially click the referral link, making Invites an excellent way to build your app’s user base.\n\nThis post is part of The Complete Guide to Firebase. Throughout this tutorial, the official documentation may be useful:\n\nImplementation\n\nAs always, the entire Firebase Reference Project is open source, and there is a pull request for adding Firebase Invites if you just want to see the code changes required. This tutorial assumes you already have Firebase added to your project.\n\nIn this tutorial, you’ll learn how to add the ability for users to send out invite links, and identify if a user has come from an invite link.\n\nAdding Firebase Invites to your project\n\nFirst, visit the Dynamic Links tab in the Firebase console, and agree to the terms of service (if necessary). Don’t worry if there’s no terms of service to agree, it only occurs in some situations!\n\nNext, add Firebase Invites by adding the following to your dependencies in your app-level build.gradle file, then perform a Gradle sync:\n\nimplementation 'com.google.firebase:firebase-invites:16.0.5'\n\n\nSending invites\n\nDisplaying invite screen\n\nThe invite screen allows the user to customise the invite message, and select one or more email / SMS contacts. In the image below, you can see a user with SMS only (chat icon), email only (envelope icon), and both (envelope icon with arrow). Email addresses and phone numbers can also be manually entered.\n\nTo actually display this dialog, pass an AppInviteInvitation to startActivityForResult(), which can be customised using the builder. Only the dialog title and invitation message must be defined, the rest are optional.\n\nprivate fun sendInviteOnClick() = activity!!\n        .startActivityForResult(\n                AppInviteInvitation.IntentBuilder(\"Share an invite!\")\n                        .setMessage(\"Here is the custom message inside the invitation!\")\n                        .setDeepLink(Uri.parse(\"https://firebasereference.jakelee.co.uk/deeplink\"))\n                        .setCustomImage(Uri.parse(\"https://via.placeholder.com/600x600/4286f4/000000?text=Invite+image!\"))\n                        .setCallToActionText(\"Accept invite\")\n                        .build(), INVITE_REQUEST_CODE)\n\n\n\n  setMessage defines the text at the top of the invite dialog.\n  setDeepLink defines the deep link that should be retrieve when an invited user opens the app.\n  setCustomImage allows you to specify an image that should be sent along with email invites.\n  setCallToActionText allows you to specify the text on the invite button in the email. Note that during my implementation, this didn’t seem to have any effect.\n  setEmailHtmlContent and setEmailSubject can also be used to completely replace the email invitation.\n\n\nINVITE_REQUEST_CODE must be under ~32k, and identifies the result returned when the user closes the dialog.\n\nAlerting user to sent invites\n\nWhen the user closes the dialog, either due to successfully inviting other users or pressing back, onActivityResult is called. This is called on your activity, even if you started the dialog from a fragment!\n\nOnce the requestCode and resultCode have been checked, the data object can be passed to AppInviteInvitations to get a list of invitation IDs. These IDs are useful for keeping track of which invites have been accepted, since they are also available when opening an invite link.\n\noverride fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {\n    super.onActivityResult(requestCode, resultCode, data)\n    if (requestCode == InvitesFragment.INVITE_REQUEST_CODE) {\n        if (resultCode == Activity.RESULT_OK) {\n            val ids = AppInviteInvitation.getInvitationIds(resultCode, data!!)\n            val idsString = ids.joinToString()\n            Toast.makeText(this, \"Invited: $idsString\", Toast.LENGTH_LONG).show()\n        } else {\n            Toast.makeText(this, \"Invite sending failed / cancelled: $resultCode\", Toast.LENGTH_LONG).show()\n        }\n    }\n}\n\n\nReceiving invites\n\n\n  \n    \n      Text\n      Email\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nWhen a user clicks the dynamic invite link from an email or text, they are taken directly to your app (or to the Play Store to install your app). When this happens, you need to check with Firebase Dynamic Links if there are any unprocessed invitations. Note that this function returns success even if there are no new invites, the difference is in whether data is null or not.\n\nThis logic should be included on every activity / fragment in your app where you want to check the user’s invite status, which is likely to be almost all.\n\nprivate fun processPendingInvite() = FirebaseDynamicLinks.getInstance()\n        .getDynamicLink(activity!!.intent)\n        .addOnSuccessListener { data -&gt;\n            if (data == null) {\n                Log.d(\"Invites\", \"getInvitation: no data\")\n            } else {\n                val deepLink = data.link\n                val inviteId = FirebaseAppInvite.getInvitation(data).invitationId\n                Toast.makeText(activity!!, \"Retrieved deep link of $deepLink and an inviteId of $inviteId\", Toast.LENGTH_LONG).show()\n            }\n        }\n        .addOnFailureListener { Log.e(\"Invites\", \"Failed\") }\n\n\nDespite the documentation’s claims, invitations do not reset themselves once used! Once getDynamicLink has returned an invitation, calling it again will return the same information. It is unknown if this is intentional, or a bug (version 16.0.5).\n\nAdditional notes\n\nAll SMS and Email invites use the user’s Google Play details. Whilst this is fine for SMS, emails are often sent to spam folders. Additionally, the partially customised email invites don’t seem to format very well. As such, using setEmailHtmlContent and setEmailSubject is recommended, to fully customise the invitation link.\n\nConclusion\n\nFirebase Invites is a relatively simple to implement referral system, and whilst it does have a very limited feature set, it performs those features reliably. The best practices article provides a few useful tips, and there are two excellent simple implementations on the case studies page.\n\nThe basic referral system may be useful for simple apps, especially those where a user is likely to download &amp; register for an app just to view a specific piece of content. However, a server should be used for management of these invite links, such as checking if an invite has been accepted. Surprisingly few games also use the feature, despite their dependence on referral &amp; invite mechanics.\n\nIt’s also worth noting that for opening a related iOS app, setOtherPlatformsTargetApplicationmust be used when displaying the invite dialog.\n"
    } ,
  
    {
      "tags"     : "Design, Splash Screen, UX",
      "title"    : "Adding A Splash Screen To An Android App",
      "excerpt"  : "Often, an app may take a few seconds to start-up, especially the first time. A plain white screen is shown by default, luckily this can be customised relatively easily! The solution is to add a splash screen to your app, whilst being careful to avoid increasing the app’s load time.\n",
      "url"      : "/adding-a-splash-screen-to-an-android-app/",
      "date"     : "Nov 27, 2018",
      "content"  : "Often, an app may take a few seconds to start-up, especially the first time. A plain white screen is shown by default, luckily this can be customised relatively easily! The solution is to add a splash screen to your app, whilst being careful to avoid increasing the app’s load time.\n\nMany naïve splash screens actually make the app take longer to load by introducing an artificial delay. The approach in this tutorial doesn’t increase load time, and only displays as long as the app loads. An example implementation is available.\n\nFirst, add a design for the splash screen and name it splash_screen_background.xml inside /drawable/. For this example, a new drawable ic_time was created and layered on top of the default colorPrimary.\n\n&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;layer-list xmlns:android=\"http://schemas.android.com/apk/res/android\" android:opacity=\"opaque\"&gt;\n    &lt;item android:drawable=\"@color/colorPrimary\" /&gt;\n    &lt;item&gt;\n        &lt;bitmap\n                android:gravity=\"center\"\n                android:scaleType=\"centerInside\"\n                android:src=\"@drawable/ic_time\" /&gt;\n    &lt;/item&gt;\n&lt;/layer-list&gt;\n\n\nUnfortunately, this can’t be a normal XML layout, and must instead be an XML drawable. Layer lists are used for the most common splash screens; coloured background with an icon in the middle. This may take some experimentation, as scaling the image correctly can be tricky.\n\nNext, add a new style SplashScreen to your styles.xml, this is the style for the splash screen and uses your newly created background:\n\n&lt;style name=\"SplashScreen\" parent=\"Theme.AppCompat.NoActionBar\"&gt;\n    &lt;item name=\"android:windowBackground\"&gt;@drawable/splash_screen_background&lt;/item&gt;\n&lt;/style&gt;\n\n\nNow set your starting activity (e.g. MainActivity) to use your SplashScreen style inside AndroidManifest.xml:\n\n&lt;activity\n        android:name=\".MainActivity\"\n        android:theme=\"@style/SplashScreen\"&gt;\n\n\nFinally, call setTheme(R.style.AppTheme) at the start of your MainActivity‘s onCreate, e.g.:\n\noverride fun onCreate(savedInstanceState: Bundle?) {\n    setTheme(R.style.AppTheme)\n    super.onCreate(savedInstanceState)\n    setContentView(R.layout.activity_main)\n}\n\n\nYour application will now use the activity’s default splash screen theme until onCreate is called, when it will load the normal theme!\n\nFor testing, it’s often handy to add a sleep(5000) before setting the theme on onCreate, otherwise the app loads too quickly to get a long look at the splash screen. Drawables inside your splash screen background should also be non-vector images, as parsing the vectors often causes unexpected effects.\n\nFull implementation source code: https://github.com/JakeSteam/SplashScreenDemo\n"
    } ,
  
    {
      "tags"     : "Kotlin, Modules",
      "title"    : "How To Display App Version Inside a Submodule",
      "excerpt"  : "Usually, getting the current version code of your app is as simple as BuildConfig.VERSION_CODE. Easy! However, this doesn’t work if you want to retrieve your app’s version code whilst inside a submodule. Instead, the submodule‘s version code is returned.\n",
      "url"      : "/how-to-display-app-version-inside-a-submodule/",
      "date"     : "Nov 26, 2018",
      "content"  : "Usually, getting the current version code of your app is as simple as BuildConfig.VERSION_CODE. Easy! However, this doesn’t work if you want to retrieve your app’s version code whilst inside a submodule. Instead, the submodule‘s version code is returned.\n\nThe solution is to use the package manager to get your application’s PackageInfo. Next, the versionCode and versionName can be retrieved (if in a fragment, replace this with activity?):\n\ntry {\n    val info = this.packageManager?.getPackageInfo(this.packageName, 0)\n    val versionName = info?.versionName\n    val versionCode = info?.versionCode\n} catch (e: PackageManager.NameNotFoundException) {\n    Timber.e(e)\n}\n\n\nNote that whilst technically a NameNotFoundException can be thrown, since you’re looking up your own app it’s a safe bet that it exists on the device! Additionally, there is a lot of other information available from the PackageInfo object returned, with no extra permissions required.\n\n\n"
    } ,
  
    {
      "tags"     : "Crashlytics, Firebase, Kotlin",
      "title"    : "Ensuring Your Android App's Quality With Firebase Crashlytics",
      "excerpt"  : "Firebase Crashlytics provides an extremely powerful automatic crash reporting tool for Android (and iOS) apps. In addition to providing a full stack trace for all crashes, it also tracks all ANRs (App Not Responding) in your app. All crashes / ANRs come with lots of metadata about the device, operating system, and can be enhanced with custom data\n",
      "url"      : "/ensuring-your-android-apps-quality-with-firebase-crashlytics/",
      "date"     : "Nov 25, 2018",
      "content"  : "Firebase Crashlytics provides an extremely powerful automatic crash reporting tool for Android (and iOS) apps. In addition to providing a full stack trace for all crashes, it also tracks all ANRs (App Not Responding) in your app. All crashes / ANRs come with lots of metadata about the device, operating system, and can be enhanced with custom data\n\nThis data is then aggregated, and widespread issues can be quickly identified and prioritised. Unlimited Crashlytics usage is provided for free, and basic integration can be completed in a couple of minutes.\n\nThis post is part of The Complete Guide to Firebase. Throughout this tutorial, you’ll need access to the Firebase Crashlytics dashboard, and the official documentation may be useful.\n\nImplementation\n\nAs always, the entire Firebase Reference Project is open source, and there is a pull request for adding Firebase Crashlytics if you just want to see the code changes required. This tutorial assumes you already have Firebase added to your project.\n\nIn this tutorial, you’ll learn how to implement Crashlytics into your existing app. You’ll also learn how to customise these crash reports, receive crash reports through various platforms, and view your crashes online.\n\nSetting up Crashlytics\n\nWeb interface\n\nOn the Crashlytics web interface, click “Set up Crashlytics”, then select “This app is new to Crashlytics” and press next. That’s it, Crashlytics is now listening for crashes, time to make your app send them!\n\n\n\nProject-level build.gradle\n\nIn your project-level build.gradle, add the following inside buildscript -&gt; repositories:\n\nmaven {\n    url 'https://maven.fabric.io/public'\n}\n\n\nAnd inside buildscript -&gt; dependencies:\n\nclasspath 'com.google.gms:google-services:4.2.0'\nclasspath 'io.fabric.tools:gradle:1.26.1'\n\n\nFinally, inside allprojects -&gt; repositories:\n\nmaven {\n    url 'https://maven.google.com/'\n}\n\n\nApp-level build.gradle\n\nAt the top of the file, add:\n\napply plugin: 'io.fabric'\n\n\nFinally, inside dependencies:\n\nimplementation 'com.google.firebase:firebase-core:16.0.4'\nimplementation 'com.crashlytics.sdk.android:crashlytics:2.9.6'\n\n\nNow, perform a Gradle sync. Crashlytics is enabled! You can test this by throwing any exception, or using the built-in Crashlytics.getInstance().crash().\n\nEnabling &amp; disabling crash reporting\n\nBy default, Crashlytics will run automatically. However, if you want to disable crash reporting until a certain time (e.g. the user accepts their crash data being shared), it can be enabled on demand. Note that crash reporting cannot be turned off programmatically, the user must restart the app. First, disable Firebase in your AndroidManifest.xml:\n\n &lt;meta-data\n      android:name=\"firebase_crashlytics_collection_enabled\"\n      android:value=\"false\" /&gt;\n\n\nNow, at whichever point in the user flow you want to enable Crashlytics, you need to initialise it:\n\nFabric.with(this, new Crashlytics());\n\n\nAll crashes / ANRs will now be recorded.\n\nAdding custom logs &amp; data to Crashlytics\n\nLogging\n\nIf you are already using Firebase Analytics, any screen view events in there will appear under the “Logs” tab of your crash.\n\n\n\nYou can also add your own events to this log manually. These can be added with Crashlytics.log(\"Your log message\"), and will then show up in your logs.\n\nKeys\n\nYou can also add custom “keys” to your crashes. This is useful for recording the current state of a user when the crash occurred, for example if they are a new or returning user. This is done using Crashlytics.setString, .setBool, setDouble, setFloat, or setInt. These functions all take a key string (e.g. “isNewUser”), and a value (e.g. “true”). These can be overwritten at any time.\n\nIdentifiers\n\nIt is often useful to know exactly which user experienced the crash, so you can work towards reproducing and eventually fixing the issue. This is done by calling Crashlytics.setUserIdentifier(\"user1234\").\n\nReceiving Crashlytics alerts\n\nBy default, you will receive email warning (shown below) of all fatal crashes with your app, so that you can respond as soon as possible.\n\n\n\nAdditionally, you can add Slack integration to Crashlytics, as well as Jira, BigQuery, and more. These integrations can be managed via the settings icon in the top left, then “Project settings”, and the “Integrations” tab. Once this has been configured, you can receive instant notifications of all crashes (or only fatal issues) in your chosen Slack channel. This can be extremely useful for teams that tend to not monitor their email too closely, as it means any issue can immediately be investigated.\n\n\n\nAdditional Crashlytics functionality\n\nCrashlytics’ core functionality of bug reporting is very powerful by itself, but it can be improved with additional functionality. For example, all new issues can be responded to in Firebase Cloud Functions via the crashlytics.issue().onNew() trigger. Additionally, regressed (onRegressed()) and large issue volume increases (onVelocityAlert()) are available to listen to. An official Firebase guide is available for this.\n\nTo allow Crashlytics to automatically deobfuscate your ProGuarded stack traces, make sure to remove -printmapping mapping.txt from your ProGuard config, and add:\n\n-keepattributes SourceFile,LineNumberTable        # Keep file names and line numbers.\n-keep public class * extends java.lang.Exception  # Optional: Keep custom exceptions.\n\n\nWeb interface\n\nCrashlytics’ web interface is a dashboard showing a record of all recent crashes, and how many users are encountering them. A summary of all encountered crashes is also shown.\n\n\n\nThe rest of the page is dedicated to listing all encountered crashes. Clicking any of these will provide metadata such as app versions that are crashing, devices encountering it, and detailed information about the crash. This detailed information consists of a full stack trace, information about the user’s devices, and any custom logs / data that has been added.\n\n\n\nConclusion\n\nFirebase Crashlytics is an extremely powerful automatic crash reporter, and is unlikely to be surpassed by any alternatives. Due to the unlimited free usage, simple integration, and ability to integrate with third party systems, it’s hard to see any major drawbacks. In 2015, it was used in 42% of the top 200 apps, and this figure has only grown since then. As such, the system has a very reliable history, and should almost always be the choice for crash monitoring.\n\nIt’s worth noting that the product has a rather complex history. Unlike most Firebase services which are developed in-house by Google, Crashlytics was originally a start-up (2011), then owned by Twitter (2013), then became a part of Fabric (2014), and is now owned by Google (2017)! The final transition is due to Fabric shutting down, with support ending in mid-2019. Migration is simple with Fabric / Google’s guide, hopefully Crashlytics has a permanent home now!\n\nPrevious: Developing Android Apps With Firebase ML Kit\n"
    } ,
  
    {
      "tags"     : "Firebase, Kotlin, Machine Learning, ML Kit",
      "title"    : "Developing Android Apps With Firebase ML Kit",
      "excerpt"  : "Machine Learning is, at its core, a way of letting programs learn how to do things by example. It can be used to get a program to self-learn how to play Mario, or how to walk. In this tutorial, Firebase’s Machine Learning Kit (commonly known as ML Kit) will be used to retrieve text, faces, barcodes, and objects from an image.\n",
      "url"      : "/developing-android-apps-with-firebase-ml-kit/",
      "date"     : "Nov 21, 2018",
      "content"  : "Machine Learning is, at its core, a way of letting programs learn how to do things by example. It can be used to get a program to self-learn how to play Mario, or how to walk. In this tutorial, Firebase’s Machine Learning Kit (commonly known as ML Kit) will be used to retrieve text, faces, barcodes, and objects from an image.\n\nFirebase’s API provides “models” (knowledge based on data sets) for common actions such as identifying faces or objects in images. Firebase also provides the ability to utilise custom models (via TensorFlow), but only the built-in models will be covered in this tutorial. Additionally, only on-device APIs will be utilised, as cloud APIs require paid plans.\n\nThis post is part of The Complete Guide to Firebase. Throughout this tutorial, the official documentation may be useful.\n\nImplementation\n\nAs always, the entire Firebase Reference Project is open source, and there is a pull request for adding Firebase ML Kit if you just want to see the code changes required. This tutorial assumes you already have Firebase added to your project.\n\nIn this tutorial, an image will be picked from a file selector, then analysed using ML Kit for relevant information. This image can also be provided via a video stream or a camera, but using an existing file is the simplest to demonstrate the core concepts. For each ML Kit model, a raw image and analysed screenshot is provided too.\n\nSetting up Firebase ML Kit\n\nFirst, add the ML Kit library to your app-level build.gradle:\n\nimplementation 'com.google.firebase:firebase-ml-vision:18.0.1'\n\n\nNext, add the models you’ll be using to your AndroidManifest.xml as a meta-data entry. This allows your app to automatically download the model when your app is installed, instead of waiting until they are actually needed. The following example includes all models used in this tutorial:\n\n&lt;meta-data\n    android:name=\"com.google.firebase.ml.vision.DEPENDENCIES\"\n    android:value=\"ocr,face,barcode,label\" /&gt;\n\n\nObtaining a target picture\n\nFor the example app, we first define a request code for each of the 4 potential ML Kit actions to be performed (Text, Face, Barcode, or Object). These can be any number under 65535, and are used to distinguish requests:\n\nprivate val TEXT_RESPONSE = 3331\nprivate val FACE_RESPONSE = 3442\nprivate val BARCODE_RESPONSE = 4443\nprivate val LABEL_RESPONSE = 4143\n\n\nNext, a button is created for each ML Kit identifying API demonstrated (Text, Face, Barcode, Object). Example XML is available, but the layout doesn’t matter. Each of these buttons then has an onClickListener set, which opens the system’s file picker, filtered to images only:\n\ntextButton.setOnClickListener {\n    startActivityForResult(\n        Intent(Intent.ACTION_GET_CONTENT).setType(\"image/*\"), TEXT_RESPONSE)\n}\nfaceButton.setOnClickListener {\n    startActivityForResult(\n            Intent(Intent.ACTION_GET_CONTENT).setType(\"image/*\"), FACE_RESPONSE)\n}\nbarcodeButton.setOnClickListener {\n    startActivityForResult(\n            Intent(Intent.ACTION_GET_CONTENT).setType(\"image/*\"), BARCODE_RESPONSE)\n}\nobjectButton.setOnClickListener {\n    startActivityForResult(\n            Intent(Intent.ACTION_GET_CONTENT).setType(\"image/*\"), LABEL_RESPONSE)\n}\n\n\nOnce the user picks an image, onActivityResult is then called. Once the resultCode has been checked, an Uri of the image can be created using Uri.parse(data!!.dataString). This Uri can then be passed to FirebaseVisionImage.fromFilePath(context, uri) to obtain the image in the required format.\n\nThis image (after updating the layout’s preview) is then passed to the appropriate function based on the desired ML Kit operation to be performed:\n\noverride fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {\n    super.onActivityResult(requestCode, resultCode, data)\n    if (resultCode != RESULT_OK) return\n    val uri = Uri.parse(data!!.dataString)\n    val image = FirebaseVisionImage.fromFilePath(activity!!, uri)\n    imagePreview.setImageBitmap(image.bitmapForDebugging)\n    output.text = \"\"\n    when (requestCode) {\n        TEXT_RESPONSE -&gt; retrieveText(image)\n        FACE_RESPONSE -&gt; retrieveFace(image)\n        BARCODE_RESPONSE -&gt; retrieveBarcode(image)\n        LABEL_RESPONSE -&gt; retrieveLabels(image)\n    }\n}\n\n\nUsing ML Kit on target picture\n\nFor all of the following code examples, image is the FirebaseVisionImage passed from onActivityResult.\n\nRetrieving text from an image\n\nFirst, make sure ocr is in your DEPENDENCIES meta-data in your AndroidManifest.xml.\n\nNext, calling firebase.onDeviceTextRecognizer.processImage(image) performs an OCR task using ML Kit. The added success listener contains a FirebaseVisionText object. This object (and all text objects below it) all have a .text available that will provide the extracted text. Additionally, all child objects have boundingBox / cornerPoints (the area scanned for this object), confidence (certainty in the text result), and recognizedLanguages (the identified languages).\n\nInside this overall summary object, there are blocks containing lines containing words containing letters. The following function loops through every word to create a count of all blocks, lines, words, and letters.\n\nprivate fun retrieveText(image: FirebaseVisionImage) {\n    FirebaseVision.getInstance()\n            .onDeviceTextRecognizer\n            .processImage(image)\n            .addOnSuccessListener { textObject -&gt;\n                var blocks = 0\n                var lines = 0\n                var words = 0\n                val letters = textObject.textBlocks.sumBy { block -&gt;\n                    blocks += 1\n                    block.lines.sumBy { line -&gt;\n                        lines += 1\n                        line.elements.sumBy { word -&gt;\n                            words += 1\n                            word.text.length\n                        }\n                    }\n                }\n                output.text = String.format(getString(R.string.mlkit_text_data),\n                        blocks, lines, words, letters, textObject.text)\n            }\n            .addOnFailureListener { output.text = it.localizedMessage }\n}\n\n\n\n  \n    \n      Input\n      Output\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nDetecting faces in an image\n\nFirst, make sure face is included in your DEPENDENCIES meta-data inside AndroidManifest.xml and the face detection dependency has been added alongside core ML Kit:\n\nimplementation 'com.google.firebase:firebase-ml-vision:18.0.1'\nimplementation 'com.google.firebase:firebase-ml-vision-face-model:17.0.2'\n\n\nNext, a FirebaseVisionFaceDetectorOptions needs to be built. There are 5 toggleable options within:\n\n\n  setPerformanceMode() can be FAST (default) or ACCURATE. Accurate is useful for static image analysis.\n  setLandmarkMode() can be NO_LANDMARKS (default) or ALL_LANDMARKS. This feature is useful when the position of specific facial features are needed.\n  setContourMode() can be NO_CONTOURS (default) or ALL_CONTOURS. This feature is useful for getting the outlines of specific facial features.\n  setClassificationMode() can be NO_CLASSIFICATIONS (default) or ALL_CLASSIFICATIONS. This feature is useful when information such as likelihood of smiling / eyes being open is needed.\n  enableTracking() enabled assigning IDs to faces. When enabled, this identifies users across multiple images.\n\n\nContours and face tracking cannot currently both be enabled at the same time. As such, for this example we’ll enable everything except contours:\n\nval options = FirebaseVisionFaceDetectorOptions.Builder()\n        .setPerformanceMode(FirebaseVisionFaceDetectorOptions.ACCURATE)\n        .setLandmarkMode(FirebaseVisionFaceDetectorOptions.ALL_LANDMARKS)\n        .setClassificationMode(FirebaseVisionFaceDetectorOptions.ALL_CLASSIFICATIONS)\n        .enableTracking()\n        .build()\n\n\nThese options are then passed to firebase.getVisionFaceDetector(options) and .detectInImage(image) is called. An (potentially empty) array of faces is returned, each of which contains information on the face’s ID, head rotation, body part positions, etc. Probabilities (eyes open, smiling) are given between 0 and 1, so multiply by 100 to get a confidence percentage. headEulerAngleY refers to the angle the head is looking left or right. 0 degrees is looking directly at the camera, negative values are looking to the left, positive values to the right (from the detected face’s perspective).\n\nFirebaseVision.getInstance()\n        .getVisionFaceDetector(options)\n        .detectInImage(image)\n        .addOnSuccessListener { faces -&gt;\n            if (faces.isEmpty()) {\n                output.text = getString(R.string.mlkit_no_faces)\n            } else {\n                var text = \"\"\n                faces.forEach {\n                    text += String.format(getString(R.string.mlkit_face_data),\n                            it.trackingId,\n                            it.leftEyeOpenProbability * 100,\n                            it.rightEyeOpenProbability * 100,\n                            it.smilingProbability * 100,\n                            it.headEulerAngleY,\n                            it.headEulerAngleZ)\n                }\n                output.text = text\n            }\n        }\n        .addOnFailureListener { output.text = it.localizedMessage }\n\n\n\n  \n    \n      Input\n      Output\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nIdentifying barcodes in an image\n\nAs usual, make sure barcode is in the android:value of your DEPENDENCIES in Android.Manifest.xml:\n\n&lt;meta-data\n    android:name=\"com.google.firebase.ml.vision.DEPENDENCIES\"\n    android:value=\"barcode\" /&gt;\n\n\nThen, create a FirebaseVisionBarcodeDetectorOptions object with all the barcode types wanted. QR Code, UPC, and EAN are the 3 most common formats.\n\nval options = FirebaseVisionBarcodeDetectorOptions.Builder()\n        .setBarcodeFormats(\n                FirebaseVisionBarcode.FORMAT_QR_CODE,\n                FirebaseVisionBarcode.FORMAT_AZTEC,\n                FirebaseVisionBarcode.FORMAT_UPC_A,\n                FirebaseVisionBarcode.FORMAT_UPC_E,\n                FirebaseVisionBarcode.FORMAT_EAN_13)\n        .build()\n\n\nNext, pass this to firebase.getVisionBarcodeDetector(options) and call detectInImage(image). This will return a list of barcodes detected, each of which contains the raw text, the computed value, and the type. For example, a TYPE\\_GEO QR code will have a rawText of geo:40.1234,75.1234,100, a type of TYPE_GEO, and a geoPoint object with lat and lng doubles. Using the raw text is generally safest, as all data types resolve to a sensible plain text.\n\nFirebaseVision.getInstance()\n        .getVisionBarcodeDetector(options)\n        .detectInImage(image)\n        .addOnSuccessListener { barcodes -&gt;\n            if (barcodes.isEmpty()) {\n                output.text = getString(R.string.mlkit_no_barcode)\n            } else {\n                var string = \"\"\n                barcodes.forEach {\n                    string += String.format(getString(R.string.mlkit_barcode_data),\n                            it.rawValue,\n                            getBarcodeType(it.valueType))\n                }\n                output.text = string\n            }\n        }\n        .addOnFailureListener { output.text = it.localizedMessage }\n\n\n\n  \n    \n      Input\n      Output\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nLabelling all objects in an image\n\nThe on-device version of this API returns the most common 400+ items, whereas the paid cloud API uses 10,000+ items. However, the local API is still very powerful, and easily detects surroundings and objects.\n\nAs always, first add label to your DEPENDENCIES inside your AndroidManifest.xml. Then add the image labelling library to your app-level build.gradle:\n\nimplementation 'com.google.firebase:firebase-ml-vision:18.0.1'\nimplementation 'com.google.firebase:firebase-ml-vision-image-label-model:17.0.2'\n\n\nThe only option for FirebaseVisionLabelDetector is the minimum confidence (0 to 1) threshold to display a result, and won’t be used in this example. Calling firebase.visionLabelDetector.detectInImage(image) will return a list of FirebaseVisionLabel. Each of these contains a label (the detected object’s name), confidence (the confidence that the object has been detected), and an entityId (a unique ID of the object).\n\nprivate fun retrieveLabels(image: FirebaseVisionImage) {\n    FirebaseVision.getInstance()\n            .visionLabelDetector\n            .detectInImage(image)\n            .addOnSuccessListener { labels -&gt;\n                if (labels.isEmpty()) {\n                    output.text = getString(R.string.mlkit_no_label)\n                } else {\n                    var string = \"\"\n                    labels.forEach {\n                        string += String.format(getString(R.string.mlkit_label_data),\n                                it.label, it.confidence * 100)\n                    }\n                    output.text = string\n                }\n            }\n            .addOnFailureListener { output.text = it.localizedMessage }\n}\n\n\n\n  \n    \n      Input\n      Output\n    \n  \n  \n    \n      \n      \n    \n  \n\n\nWeb interface\n\nThe APIs tab of the web interface shows all APIs currently in use by your apps, as well as which package name is utilising it.\n\n\n\nConclusion\n\nFirebase’s ML Kit provides an excellent introduction to the power of machine learning assisted image analysis. Whilst the OCR, object identification, barcode reading, and facial recognition are just examples, the models are extremely powerful already. Considering the free and offline nature of these models, they are perfect for almost any implementation.\n\nHowever, the very nature of the image analysis technique means that there is no debug information available. The high success rate of the models should prevent this being an issue, but the lack of information is worth keeping in mind.\n\nFrom my own experimentation, the facial analysing performed amazingly well, as did the object recognition. However, somewhat surprisingly, the text identification was much less successful. This is likely due to the large number of fonts available, as well as the similarity between many letters, but it’s still unusual that the most common use case is the least accurate!\n\nPrevious: Developing Android Apps With Firebase Cloud Storage\n\nNext: Ensuring Your Android App’s Quality With Firebase Crashlytics\n"
    } ,
  
    {
      "tags"     : "Cloudflare, Firebase, Hosting",
      "title"    : "Developing Web Apps With Firebase Hosting",
      "excerpt"  : "Firebase hosting provides an extremely simple way to deploy JavaScript web apps. Whilst it lacks almost all of the advanced features other hosts have, it does have the major advantage of being free for low-traffic usage. This tutorial will cover creating a basic site, as well as utilising a custom subdomain with Cloudflare.\n",
      "url"      : "/developing-web-apps-with-firebase-hosting/",
      "date"     : "Nov 19, 2018",
      "content"  : "Firebase hosting provides an extremely simple way to deploy JavaScript web apps. Whilst it lacks almost all of the advanced features other hosts have, it does have the major advantage of being free for low-traffic usage. This tutorial will cover creating a basic site, as well as utilising a custom subdomain with Cloudflare.\n\nThis post is part of The Complete Guide to Firebase. Throughout this tutorial, you’ll need access to the Firebase Hosting dashboard, and the official documentation may be useful too.\n\nImplementation\n\nAs always, the entire Firebase Reference Project is open source, and the hosted code is available as a repository. There is also a pull request for the very minor changes made to the Android reference app.\n\nSetting up Firebase Hosting environment\n\n\n  First install npm &amp; node.js, used to handle the Firebase installation process.\n  Next, open a Command Prompt and enter npm install -g firebase-tools, after a few minutes you should see something similar to the following image:\n  Next, login to your Firebase account using firebase login. This will open a browser with a login request. Once logged in, the Command Prompt will report success.\n  Next, navigate to the directory you want to deploy code from.\n  Enter firebase init to initialise a local Firebase project. You will be prompted to choose a service (choose “Hosting”), and a Firebase project to use.\n  Finally, pick a folder to use for your public files (default is “public”), and whether you want a single page web app (this can be changed later).\n\n\nDeploying Firebase Hosting site\n\nDeploying your site is very easy, just enter firebase deploy and within a few seconds the updated files are published. That’s it! The same process is used for the initial deployment as well as all subsequent deployments.\n\n\n\nSetting up a custom subdomain with Cloudflare\n\nBy default, your project will have a URL like https://fir-referenceproject.firebaseapp.com/. However, custom domains / subdomains can be added within a minute or two by following the simple steps displayed when “Connect domain” is pressed.\n\nDefine custom URL\n\nFirst, enter your custom URL. I’ll be using https://firebasehosting.jakelee.co.uk.\n\nVerify domain ownership\n\nNext, you need to prove you own the URL. This is done by adding a TXT record in your domain’s DNS, accessible under the “DNS” tab in Cloudflare.\n\n \n\nAdd A records\n\nFinally, you now need to add the actual A records that will allow Firebase to serve content for your URL. This is done by adding 2 entries, each with your target subdomain as the “Name”, and the specified IPs as the “IPv4 Address”.\n\n \n\nWeb interface\n\nFirebase Hosting’s very limited function set is easily seen when accessing the web interface. Each tab provides the bare essentials, and sometimes not even that!\n\nDashboard\n\nThe dashboard displays a list of all connected custom domains, and a list of all releases. Previous releases can be easily rolled back to or deleted, but no information is available about them. As such, an external source code manager like Git will still be essential for development.\n\n\n\nUsage\n\nThe usage tab shows 2 simple graphs; your storage space used over time, and your data transfer size over time. The free “Spark” plan has a limit of 1GB of storage space, and 10GB/month of data transfer.\n\n\n\nConclusion\n\nBefore judging Firebase Hosting too harshly, it’s important to remember that this isn’t meant to replace traditional web hosts. Instead, it is intended as an extremely quick &amp; simple way to have a web app live on the internet, with CDN + HTTPS + custom domain, for free. Whilst it absolutely can be used for production-level apps, the lack of any controls may make even the most cutting-edge web developer a little bit hesitant.\n\nConsidering the amazingly easy to use deployment process, and the industry standard features offered for free, Firebase Hosting is definitely a contender for quick site prototypes. It can also hook into Firebase Cloud Functions to handle server / database communication or data transfer with other systems.\n\nI personally will most likely use it next time a simple idea needs testing, and eagerly await being up and running within a minute or two!\n\nPrevious: Developing Android Apps With Firebase Cloud Storage\n"
    } ,
  
    {
      "tags"     : "Cloud Storage, Firebase, Kotlin",
      "title"    : "Developing Android Apps With Firebase Cloud Storage",
      "excerpt"  : "Firebase Cloud Storage provides an easy way to store user’s files, or provide existing files to the user. Additionally, heavily customisable access control is included, and all files can be browsed via a web interface. In this tutorial’s implementation, the user will be able to download sample files, and upload / delete their own arbitrary files.\n",
      "url"      : "/developing-android-apps-with-firebase-cloud-storage/",
      "date"     : "Nov 19, 2018",
      "content"  : "Firebase Cloud Storage provides an easy way to store user’s files, or provide existing files to the user. Additionally, heavily customisable access control is included, and all files can be browsed via a web interface. In this tutorial’s implementation, the user will be able to download sample files, and upload / delete their own arbitrary files.\n\nThis post is part of The Complete Guide to Firebase. Throughout this tutorial, you’ll need access to the Firebase Cloud Storage dashboard, and the official documentation may be useful too.\n\nImplementation\n\nAs always, the entire Firebase Reference Project is open source, and there is a pull request for adding Firebase Cloud Storage if you just want to see the code changes required.\n\nThis tutorial assumes you already have Firebase added to your project.\n\nSetting up Firebase Cloud Storage environment\n\nVisiting the Cloud Storage dashboard and clicking “Get Started” will display a dialog confirming the default security rules. These rules state that any logged-in users can read and write any files, a relatively lax default ruleset! Once these default rules have been agreed to, you’ll have an empty storage “bucket”, ready to fill up with files.\n\n\n\nNavigate to the rules tab, and the default rules from earlier will be visible. Whilst these rules can be intricately applied, in this use case 2 directories will be configured; one non-writable (sample) and one writable (userFolder). The following config is very straightforward, and configures the 2 directories and all subdirectories / files inside them. Additionally, a maximum filesize of 5MB (5 * 1024 * 1024 bytes) will be implemented to prevent excessive storage usage. The latter part of the conditional statement (|| request.resource == null) is to allow file deletion.\n\nservice firebase.storage {\n  match /b/{bucket}/o {\n    match /sample/{allPaths=**} {\n      allow read;\n    }\n    match /userFolder/{allPaths=**} {\n      allow read;\n      allow write: if request.resource.size &lt; 5 * 1024 * 1024 || request.resource == null\n    }\n  }\n}\n\n\nFinally, to include Cloud Storage in your project, add the following to your app-level build.gradle. If you are prompted to update the library’s version number, do so.\n\nimplementation 'com.google.firebase:firebase-storage:16.0.4'\n\n\nObtaining a file reference\n\nFor all of the following tasks, first a file / directory reference will be needed. This is retrieved by:\n\n\n  Getting a Cloud Storage instance with storage = FirebaseStorage.getInstance()\n  Getting a reference with reference = storage.child(folderName)\n\n\nNow, any delete / download operations can be performed on that reference.\n\nRetrieving file metadata from Cloud Storage\n\nOn your file reference, call .metadata, followed by .addOnSuccessListener and .addOnFailureListener:\n\nprivate fun viewMetadata(reference: StorageReference) = reference.metadata\n    .addOnSuccessListener {\n        Toast.makeText(activity, \"${it.name} has a size of ${it.sizeBytes} bytes, and is a ${it.contentType}\", Toast.LENGTH_SHORT).show()\n    }\n    .addOnFailureListener {\n        Toast.makeText(activity, \"Failed to load metadata: ${it.localizedMessage}\", Toast.LENGTH_SHORT).show()\n    }\n\n\nThe StorageMetadata object returned on successful metadata retrieval contains a lot of useful information by default, and can be improved by adding custom metadata fields. It contains the name (.name), size (.sizeBytes), type (.contentType), MD5 hash (.md5Hash) and much more.\n\nDownloading a file from Cloud Storage\n\nFirst, create a local file to save the remote file into. For example, to create a temporary file with the remote file’s name prefixed by download_, use File.createTempFile(\"download_\", reference.name).\n\nThe remote file can then be copied into the local file using reference.getFile(file). Additionally, call .addOnSuccessListener and .addOnFailureListener, to end up with the following:\n\nprivate fun downloadFile(reference: StorageReference) {\n    val file = File.createTempFile(\"download_\", reference.name)\n    reference.getFile(file).addOnSuccessListener {\n        Toast.makeText(activity, \"Saved  ${reference.name} (${it.totalByteCount}bytes) to ${file.absolutePath}!\", Toast.LENGTH_LONG).show()\n    }.addOnFailureListener {\n        Toast.makeText(activity, \"Failed to download file: ${it.localizedMessage}\", Toast.LENGTH_SHORT).show()\n    }\n}\n\n\nUploading a file to Cloud Storage\n\nTo display a system dialog offering selection of any type of file (*/*), the following will be used:\n\nuploadButton.setOnClickListener {\n    startActivityForResult(\n            Intent(Intent.ACTION_GET_CONTENT).setType(\"*/*\"), 1234)\n}\n\n\nWhen the file selector is closed, onActivityResult will be called. Inside this, the actual upload will take place.\n\nFirst, check a file was successfully selected, by exiting if the resultCode != RESULT_OK. Afterwards, convert the file path string into a Uri, and take the last part to use as a filename.\n\nNext, create a reference to your target file’s location. In this example, getUserDirectory gets a unique bucket for each phone model, to avoid everyone using the same storage bucket. A reference is then created in this bucket using .child(name).\n\nFinally, .putFile() uploads the actual file, with .addOnSuccessListener and .addOnFailureListener used as callbacks.\n\noverride fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {\n    if (resultCode != RESULT_OK) return\n    val uri = Uri.fromFile(File(data!!.dataString))\n    val name = uri.lastPathSegment\n    Toast.makeText(activity, \"Beginning to upload $name\", Toast.LENGTH_SHORT).show()\n    getUserDirectory(FirebaseStorage.getInstance()).child(name).putFile(Uri.parse(data.dataString))\n            .addOnSuccessListener {\n                Toast.makeText(activity, \"Successfully uploaded $name!\", Toast.LENGTH_SHORT).show()\n                addUserFile(uri.lastPathSegment)\n                updateUserTable(FirebaseStorage.getInstance())\n            }\n            .addOnFailureListener {\n                Toast.makeText(activity, \"Failed to upload $name!\", Toast.LENGTH_SHORT).show()\n            }\n    super.onActivityResult(requestCode, resultCode, data)\n}\n\n\nThe addUserFile and updateUserTable functions in the above example can be ignored, as they are used to display files to the user in the example app.\n\nDeleting a file from Cloud Storage\n\nDeleting a file is extremely simple, just requiring calling .delete() on the file reference, along with .addOnSuccessListener and .addOnFailureListener. As with file upload, both deleteUserFile and updateUserTable are only used for the example app and can be safely ignored!\n\nprivate fun deleteFile(reference: StorageReference) = reference\n        .delete()\n        .addOnSuccessListener {\n            Toast.makeText(activity, \"Deleted  ${reference.name}!\", Toast.LENGTH_SHORT).show()\n            deleteUserFile(reference.name)\n            updateUserTable(FirebaseStorage.getInstance())\n        }.addOnFailureListener {\n            Toast.makeText(activity, \"Failed to delete file: ${it.localizedMessage}\", Toast.LENGTH_SHORT).show()\n        }\n\n\nWeb interface\n\nFiles\n\nThe files tab can be very useful when debugging. It provides a traditional view of all folders, subfolders, and files in your Cloud Storage bucket. Whilst you cannot rename files / folders, you can delete them and view file previews / metadata. Additionally, you can create new folders and upload files manually.\n\n\n\nRules\n\nThe rules tab displays your current configuration, as well as letting you test it by sending fake requests. These fake requests can be used to check if certain sections of your users have the correct permissions for various files. The fake request payload is also displayed, so you can manually enter it in request execution programs like Postman.\n\n\n\nUsage\n\nThe usage tab shows a summary of your storage space used, number of files, bandwidth used, and total requests made. There are quotas for these metrics, but they are fairly generous, even for the free plan:\n\n\n  Storage space used: 5TB\n  Number of files: Unknown\n  Bandwidth used: 1GB/day\n  Total requests: 50,000 downloads &amp; 20,000 uploads/day\n\n\n\n\nConclusion\n\nFirebase’s Cloud Storage provides an extremely easy to use way to allow users to host files, for free. Due to this, and the quite generous 5TB total storage limit, it is a serious contender for any use cases that include user files. For example, backing up user’s data to the cloud, or sharing images in a chat program.\n\nThe 1GB/day bandwidth limit may be an issue for applications that need to transfer large files often, but should be enough for smaller implementations. Of course, since it runs on Google Cloud Platform, these limits can be scaled up to suit any use case… for a cost!\n\n\n\nPrevious: Developing Android Apps With Firebase Cloud Functions\n\nNext: Developing Android Apps With Firebase ML Kit\n"
    } ,
  
    {
      "tags"     : "Locale, Localisation, Loco, Translations",
      "title"    : "Creating Multiple Translations Per Language In Loco",
      "excerpt"  : "For most translation projects, the goal is to translate the base language to other dialects. However, if you are creating an app with multiple variants, translations can also be used to localise the project to specific audiences. For example, a collection of fast food apps may have different text for Pizza, Indian, or Chinese food.\n",
      "url"      : "/creating-multiple-translations-per-language-in-loco/",
      "date"     : "Nov 8, 2018",
      "content"  : "For most translation projects, the goal is to translate the base language to other dialects. However, if you are creating an app with multiple variants, translations can also be used to localise the project to specific audiences. For example, a collection of fast food apps may have different text for Pizza, Indian, or Chinese food.\n\nManaging these text sets can be tricky, but using a translation management tool like Loco helps keep all the variants under control.\n\nWhilst Loco isn’t designed for managing multiple translations in a single language, it can be done. The secret is using a custom country code as your language tag, but this comes with a few complications.\n\nAlternative approaches, such as picking an arbitrary other language to represent a strings variant, have the massive disadvantage of confusing any future internationalization efforts.\n\nCreating a new variant\n\nTo add a locale, first press “New locale” on Loco’s sidebar. This will display the locale adding dialog, with “Basic”, “Custom”, and “Advanced” options.\n\nSelect “Advanced”. Now, enter the locale’s unique identifier. This will be your 2 letter language code, followed by a “-“ and up to 8 lowercase characters.\n\n\n\nAfter pressing “Add locale”, you’ll see a confirmation pop-up and your new locale is created!\n\n\n\nLanguage tag limitations\n\nLoco has 3 different options for subtags (the text in a language tag after the language code) with slightly different rules. Loco’s documentation provides more information on these.\n\n\n  Script: Must start with an uppercase letter, and be 2 or 4 letters long.\n  Variant: Must start with a lowercase letter, and be 2-8 letters long.\n  Extension: Must start with “x-“, then 1-8 letters / numbers long.\n\n\nMousing over a locale in the sidebar and clicking the gear icon will let you view the current configuration, including the “Custom language tag” (under the “Developer” tab).\n\nThe “Optional subtags” section shows the currently used subtag. Note that the language tag cannot be modified by changing these options, you’ll encounter a conflict with existing locales. Instead, use the “Developer” tab to do it manually. Additionally, you’ll see a warning about non-standard subtags, this is a side-effect of skipping normal locale codes!\n\n\nWarnings\n\nUnfortunately this approach comes with a few drawbacks:\n\nFirstly, changing the country’s language tag cannot be done via the subtags menu. Instead, the option is on the “Custom language tag” under the “Developer” tab of the locale settings. Luckily, it’s unlikely you’ll need to do this very often, if ever.\n\nSecondly, some export formats (specifically Android’s strings.xml) don’t properly handle multiple custom locales. Whilst SQL, JSON, HTML, iOS’ Localizable.strings and all others tested correctly include all locales, the Android export compresses them all into a single locale. Individually exporting the locales is a workaround to this relatively minor issue.\n"
    } ,
  
    {
      "tags"     : "Certification, Google Play, Training",
      "title"    : "Learning How To Manage Your Apps With Google Plays Academy for App Success",
      "excerpt"  : "A couple of weeks ago, Google announced the Academy for App Success. This online tutorial series contains 10 collections of “courses”. Each course consists of a few pages of information, useful graphics, and sometimes a question or two at the end. Every aspect of the Play Store process is likely covered somewhere, thanks to the over 60 courses offered.\n",
      "url"      : "/learning-how-to-manage-your-apps-with-google-plays-academy-for-app-success/",
      "date"     : "Nov 6, 2018",
      "content"  : "A couple of weeks ago, Google announced the Academy for App Success. This online tutorial series contains 10 collections of “courses”. Each course consists of a few pages of information, useful graphics, and sometimes a question or two at the end. Every aspect of the Play Store process is likely covered somewhere, thanks to the over 60 courses offered.\n\nAdditionally, many of the collections have a short 10-15 question multiple choice exam at the end, successful completion of which (70-80%+) will give you an award that can be displayed on your Academy for App Success profile. There are a total of 11 available, you can see them all on my profile.\n\nWhilst much of the content will be familiar to those who have published an app before, previously developers had to figure it out themselves. All information is in one structured, logical place in the Academy, hopefully meaning new developers have a much easier time getting started!\n\nThe structure of the content regularly changes to keep it interesting. For example, there are flash cards / flipcards:\n\n\n\nTabbed elements:\n\n\n\nKnowledge check quizzes:\n\n\n\nAnd even mock conversations:\n\n\n\nThe resource is definitely worth a skim through, even if you’re a seasoned Play Store publisher. It takes 2-5 hours to complete, and contains a lot of helpful tips and features that may have been gone unnoticed otherwise.\n\nGoogle Play Academy for App Success\n"
    } ,
  
    {
      "tags"     : "Automation, Backup, GitHub, Sync, Wordpress",
      "title"    : "How To Automatically Backup WordPress Posts To GitHub",
      "excerpt"  : "When programming, most developers use GitHub (or another hosted git solution) to make sure all of their work is backed up in multiple places to ensure it is never lost. If you’re anything like me, when writing blog posts you want the same peace of mind you have with the rest of your work. This post will cover how to automatically export all WordPress posts to GitHub (and keep it updated), so that they can be imported later if necessary.\n",
      "url"      : "/how-to-automatically-backup-wordpress-posts-to-github/",
      "date"     : "Nov 4, 2018",
      "content"  : "When programming, most developers use GitHub (or another hosted git solution) to make sure all of their work is backed up in multiple places to ensure it is never lost. If you’re anything like me, when writing blog posts you want the same peace of mind you have with the rest of your work. This post will cover how to automatically export all WordPress posts to GitHub (and keep it updated), so that they can be imported later if necessary.\n\nInstalling WordPress / GitHub Sync\n\nFirst, install the syncing plugin from the WordPress.org directory. This can be done by going to the “Plugins” -&gt; “Add new” page, searching for “WordPress GitHub Sync”, pressing “Install Now” and then “Activate”. You can also download and upload it manually if you prefer from the plugin’s page. Note that the plugin is open source, and can be viewed on GitHub.\n\nConfiguring settings\n\nA new option “GitHub Sync” will now appear under your Settings in the sidebar. Clicking this will take you to a somewhat complicated setup screen, here’s what goes in each field:\n\n\n\n\n  GitHub hostname: This should not need to be changed, unless you’re using a company-hosted GitHub.\n  Repository: The repository the exported posts will go into. This should be a public repository on your GitHub page, and should already have had the initialisation commit. GitHub provides a step by step guide to creating a repository if you haven’t done it before.\n  Oauth Token: This is needed to allow the plugin to perform actions (syncing) on your behalf. To create one, just visit your tokens page, fill in a description, tick public_repo, and press “Generate token”. You’ll then be shown a secret 40-character string (with a green background), copy it into the plugin’s form.\n  Webhook Secret: A webhook is needed for the repository to communicate back to the plugin. Create a new one for your GitHub repository by going to Settings -&gt; Webhooks. Fill in the form as follows:\n    \n      Payload URL: Use the Webhook callback from step 6.\n      Content type: Change to “application/json”.\n      Pick a secret password, this can be anything at all!\n      All other settings can be left at default settings.\n      Click “Add webhook”.\n    \n  \n  Default Import User: The user any posts imported from WordPress will post as. This defaults to your admin user.\n  Webhook callback: Already used for the Webhook secret.\n  Action buttons:\n    \n      Export to GitHub: This will perform an initial backup of all posts, make sure to click it.\n      Import from GitHub: This would be used when restoring a backup, it isn’t needed for this.\n    \n  \n\n\nChecking results\n\nAfter pressing “Export to GitHub” in step 7.1 above, the plugin will begin working. After a few minutes (depending on the number of posts), you should see a repository filled up with all your posts and pages. The exported post contains a row of metadata (title, URL, author, publish date, etc), then the processed (HTML) version of your post, including all images and formatting. You can see an example exported post here, from this post.\n\nNow, whenever you make a new post it will be automatically exported here. Nothing private has been exposed, as all of the posts are already publicly viewable, and the plugin’s open-source nature (and limited permissions) means it’s relatively trustworthy. I’ve been using it myself on this blog, and it’s successfully exported every post. Awesome!\n\n\n"
    } ,
  
    {
      "tags"     : "Cloud Functions, Firebase, JavaScript, Kotlin",
      "title"    : "Developing Android Apps With Firebase Cloud Functions",
      "excerpt"  : "Firebase Cloud Functions provide an easy way to execute JavaScript on Google’s servers, and call this code from your own apps. It removes the need to manually manage any sort of server, and can be up and running very quickly. Firebase’s free plan is somewhat limited, and cannot make network requests to other servers, but it can do plenty of processing.\n",
      "url"      : "/developing-android-apps-with-firebase-cloud-functions/",
      "date"     : "Nov 2, 2018",
      "content"  : "Firebase Cloud Functions provide an easy way to execute JavaScript on Google’s servers, and call this code from your own apps. It removes the need to manually manage any sort of server, and can be up and running very quickly. Firebase’s free plan is somewhat limited, and cannot make network requests to other servers, but it can do plenty of processing.\n\nThis post is part of The Complete Guide to Firebase. Throughout this tutorial, you’ll need access to the Firebase Cloud Functions dashboard, and the official documentation may be useful too.\n\nImplementation\n\nAs always, the entire Firebase Reference Project is open source, and there is a pull request for adding Firebase Cloud Functions if you just want to see the code changes required. Additionally, the hosted functions code is available as a repository.\n\nThis tutorial assumes you already have Firebase added to your project.\n\nSetting up Firebase Cloud Functions environment\n\n\n  First install npm &amp; node.js, used to handle the Firebase installation process.\n  Next, open a Command Prompt and enter npm install -g firebase-tools, after a few minutes you should see something similar to the following image:\n  Next, login to your Firebase account using firebase login. This will open a browser with a login request. Once logged in, the Command Prompt will report success.\n  Next run firebase init functions, which will ask you a few questions about your setup. Click any of the following items to view a screenshot of the installation at that point.\n    \n      The project to use, I chose my Firebase Reference Project.\n      The language to use, I chose JavaScript.\n      Whether style checker ESLint should be used &amp; dependencies should be installed, I chose “Yes” to both.\n    \n  \n  You should now have a project folder containing a few files and folders. functions/index.js is the most important file, as it contains your functions’ actual code. Open this file up and uncomment the lines relating to export.helloWorld.\n\n\nThat’s it, your local environment is now fully setup, and you’ve got a “Hello World” function ready to deploy!\n\nDeploying Firebase Cloud Functions\n\nTo deploy or update your functions, enter firebase deploy –only functions to your Command Prompt whilst inside your project directory. On Windows machines, this will fail by default due to a slightly faulty configuration (this error specifically):\n\n\n\nLuckily, fixing this is just a case of opening your firebase.json and replacing \\\\\"$RESOURCE\\_DIR\\\\\" with ./functions/. Save the changes, enter firebase deploy –only functions again, and it should now successfully deploy:\n\n\n\nOur Hello World function is now ready to call! Visiting the URL outputted (https://us-central1-fir-referenceproject.cloudfunctions.net/helloWorld) will display whatever message our Cloud Function in index.js was set to output. You now have a cloud-hosted function, congratulations! Time to make your own…\n\nCreating a Cloud Function\n\nYou may have noticed the existing Hello World functions inside index.js uses functions.https.onRequest. This means it can be visited / called like a normal webpage, and has Content-Type headers etc. Whilst you can get URL parameters from these methods (using request.query.text), it’s safer to provide actual functions that can be called remotely. There’s a reason it’s called Cloud Functions!\n\nWe’re going to create a function that receives a phone’s manufacturer’s name from the app, converts it to uppercase, and then returns it to be shown in the app. This is obviously a pretty useless function that would usually be handled entirely inside the app, but it’s a simple way to show passing data back and forth.\n\nTo do this, use functions.https.onCall instead, which can also receive a data object with any additional parameters you’ve chosen to send. We’re going to receive a manufacturer parameter, so first check it has a length, then convert whatever it contains to uppercase and return it. Add the following into your index.js:\n\nexports.uppercaseDeviceName = functions.https.onCall((data) =&gt; {\n    if (data.manufacturer.length &gt; 0) {\n        return data.manufacturer.toUpperCase();\n    }\n    return \"Unknown\";\n});\n\n\nSave and redeploy the functions, and your custom function is now ready to be called. Note that to return data we just used return x, instead of the response.send(x) required by onRequest functions. Google’s example index.js&gt; contains more complex examples that may be useful for further work.\n\nTime to programmatically call our new function from inside an app!\n\nCalling Cloud Functions from an Android app\n\nFirst, add the Firebase Cloud Functions dependency in your app-level build.gradle file and perform a sync:\n\nimplementation 'com.google.firebase:firebase-functions:16.1.2'\n\n\nNext, use the following to make a call to your new uppercaseDeviceName function, passing it a HashMap containing your device’s manufacturer (as the manufacturer key), and displaying a Toast of the result:\n\nFirebaseFunctions.getInstance()\n\t\t.getHttpsCallable(\"uppercaseDeviceName\")\n\t\t.call(hashMapOf(\"manufacturer\" to Build.MANUFACTURER))\n\t\t.continueWith { task -&gt;\n\t\t\tif (task.isSuccessful) {\n\t\t\t\tToast.makeText(activity, \"Uppercase manufacturer is: ${task.result!!.data}\", Toast.LENGTH_SHORT).show()\n\t\t\t} else {\n\t\t\t\tToast.makeText(activity, task.exception.toString(), Toast.LENGTH_SHORT).show()\n\t\t\t}\n\t\t}\n\n\nIn the example app, this is triggered inside an onClick().\n\nDue to Firebase already knowing which project you’re calling (due to the google-services.json), just passing the function’s name is enough to call the function. Pretty cool, right? If you encounter problems in getting a response from the server, the “Web interface” part of this post covers how to view server logs containing any runtime errors. ESLint should also alert you on deployment if your code contains incorrect syntax, helpful if JavaScript isn’t one of your core languages.\n\nAutomatically triggering Cloud Functions\n\nWhilst both the Hello World and Uppercase Manufacturer Name functions in this tutorial were triggered on demand, it’s also possible to automatically call cloud functions when an event happens. Using Google’s example, you could trigger functions when a new image is uploaded to Firebase Storage to store the location in Firebase Database, and create a thumbnail of the image using an external API.\n\n\n\nTo set up these triggers, define your function as a listener instead of an onCall or onRequest. For example, Cloud Firestore has onCreate, onUpdate, onDelete, and onWrite listeners. Set these up in your index.js as if they were a normal function:\n\nexports.yourFunctionName = functions.firestore\n    .document('sampledata').onWrite((change, context) =&gt; {\n      // All changes will be inside `change`\n    });\n\n\nMany Firebase services provide these listeners that your Cloud Functions can subscribe to. To see which listeners are available, please see the live documentation as all of these services are currently in Beta and subject to change:\n\n\n  Analytics\n  Authentication\n  Firestore\n  Cloud Pub/Sub\n  Cloud Storage\n  Crashlytics\n  Realtime Database\n  Remote Config\n\n\nWeb interface\n\nThe majority of Cloud Functions’ interface is in Firebase, but certain actions (e.g. deleting a function) can only be performed in Google Cloud Platform, so both will be covered.\n\nFirebase\n\nDashboard\n\nThe dashboard shows an overview of all of your current cloud functions, with basic information like region, node version, and memory allocation.\n\n\n\nHealth\n\nThe Health tab shows an overview of your functions’ error rates and overall performance (times invoked, latency, memory usage, network usage). Checking this regularly can help you stay on track of any errors, and provide a quick health check of your functions.\n\n\n\nLogs\n\nThe Logs tab provides a simple log viewer, that can be used for basic analysis of any runtime issues encountered. Logs can be searched, and filtered by function, log level, and time period. These are very useful when experiencing issues with your functions, as a full stack trace will appear here.\n\n\n\nUsage\n\nThis tab displays a simple chart of total invocations in a selected date range, and a link to your current quota. As it is essentially a repeat of the Health tab, it’s not included here!\n\nGoogle Cloud Platform\n\nAs Cloud Functions technically run on Google Cloud, some statistics can only be viewed there. After visiting the links, make sure to select the correct project using the dropdown at the top of the page.\n\nDashboard\n\nThe dashboard page shows a more comprehensive overview of all your Google Cloud services, and their recent performance.\n\n\n\nQuotas\n\nThe quotas page shows your functions’ usage against all applicable resource limits. For example, your plan is subject to read limits, write limits, CPU limits, traffic limits, DNS limits, build time limits, etc. You should occasionally check the graphs on this page to make sure no functions are misbehaving.\n\n\n\nFunctions\n\nThe Cloud Platform functions overview tab looks and functions almost exactly the same as the Firebase functions overview tab, but it has one key feature: The ability to delete functions!\n\n\n\nConclusion\n\nFirebase’s Cloud Functions service is extremely powerful, and should definitely be investigated if looking into server side processing or considering managing a server yourself.\n\nHowever, for many use cases it can be simpler to perform basic functionality client-side. Afterwards, this data can then be passed straight to Firestore or Database instead of handling it with a function. Additionally, the ability to only write code in JavaScript (or TypeScript, a slightly extended variant) severely limits the usefulness. Many Android developers will have little to no JavaScript experience, so learning a whole new language with a whole host of unique quirks can be a daunting experience.\n\nBefore rashly converting all of your node.js servers to cloud functions, consider running a test run. From this, you can see if the response times and quota fit your requirements. You may find that the ability to distribute the load over multiple regions causes unacceptable performance in some regions.\n\nPrevious: Developing Android Apps With Firebase Realtime Database\n\nNext: Developing Android Apps With Firebase Cloud Storage\n"
    } ,
  
    {
      "tags"     : "Blog, Bluehost, Cloudflare, Hosting, Migration, Wordpress",
      "title"    : "How To Migrate A Subdomain Site From WordPress.com To Another Host",
      "excerpt"  : "As you may have (hopefully not!) noticed, this blog was recently moved from WordPress.com’s hosted solution to another host, namely Bluehost. Bluehost were chosen due to being the only host recommended by both WordPress.com and WordPress.org, and their low prices. This post isn’t sponsored by them! This tutorial will walk through every step taken by myself during this process, to hopefully give you an idea of the work involved and avoid the same mistakes being made.\n",
      "url"      : "/how-to-migrate-a-subdomain-site-from-wordpress-com-to-another-host/",
      "date"     : "Nov 1, 2018",
      "content"  : "As you may have (hopefully not!) noticed, this blog was recently moved from WordPress.com’s hosted solution to another host, namely Bluehost. Bluehost were chosen due to being the only host recommended by both WordPress.com and WordPress.org, and their low prices. This post isn’t sponsored by them! This tutorial will walk through every step taken by myself during this process, to hopefully give you an idea of the work involved and avoid the same mistakes being made.\n\nNote that WordPress.com also offer a “guided transfer” for $129, but none of the steps are too challenging if you’ve got a few hours spare! Before beginning this tutorial, it’s worth pointing out that I used Cloudflare to handle my site’s subdomain being provided by a different host. If you are using a raw domain (e.g. http://example.com), or another CDN / domain registrar, the Cloudflare steps will be slightly different. The other steps will be unchanged.\n\nPreparing old blog\n\nDisable scheduled / automatic actions\n\nThe first step in transferring host is preparing your blog for the migration, so that nothing interferes with the transfer. If there are any scheduled posts, their scheduled times should be changed to a day or so later, otherwise they may get published during the transfer and not be published correctly. Next, any automatic actions hooked into your WordPress.com account need to be temporarily disabled, as they may get confused. For example, I was using IFTTT to automatically tweet blog posts on my Twitter (example). I disabled this recipe during the transfer to avoid all old posts being seen on the new blog for the first time and being tweeted. If you have plugins installed (not available on most WordPress.com plans), make sure any that may interfere are disabled.\n\nExport data\n\nTo export all of your existing pages, posts, categories, tags, and much more, WordPress luckily includes a built in exporter. This can be found at yoursite.com/wp-admin/export.php, make sure “All content” is selected for export. Clicking “Download Export File” will then queue up an export, a link to which will be emailed to you within a few minutes. \n\nThis export will consist of an XML file (technically a Wordpress Extended RSS file), which will be needed in the next step.\n\nSet up new blog\n\nOnce you’ve selected your plan, paid, and filled in all necessary information, you should have access to your new wordpress dashboard (e.g. Bluehost’s). Currently your brand new blog will have an example post, and a default theme. It’ll also be hosted on an odd domain similar to box1234.temp.domains/~yourusername. Your old blog will continue to work until you move onto the next step, Cloudflare, so take your time ensuring your new blog design is perfect before continuing.\n\nImport data\n\nTo import data, first install and activate the WordPress Importer plugin, it may even be enabled by default. Once this is done, under the “Import” page under “Tools”, the wordpress option will have a “Run importer” link, taking you to the plugin’s import page. Upload your export file from your old blog, and import it.\n\nAll posts, pages, categories, and tags should now be imported successfully, although you may notice some minor formatting issues. Many of these will be fixed in the following steps, so it’s recommended to fix any incorrectly formatted posts after all of the following steps have been completed. \n\nRepick theme\n\nAssuming you were using a built-in WordPress.com theme, it should be available in your host’s theme library. If not, it should be available in the official WordPress.org theme library. These can be previewed and installed very easily via the “Themes” page under “Appearance”.\n\nReconfigure theme\n\nYou may have configured your theme to have custom widgets in your sidebar(s). Make sure to also add these all to your new blog, you can use your old blog as a reference to ensure none are missed / misconfigured.\n\nReinstall plugins\n\nFinally, go through your plugins list and make sure they have all been installed again, copying across any configurations as necessary. This may also be a good time to trim your plugins list (/wp-admin/plugins.php), and get rid of any you don’t actually need!\n\nSet up Cloudflare / Domain Host\n\nCloudflare is going to be used to redirect all requests to your blog’s subdomain (e.g. blog.example.com) to your host. This can be a little tricky, as there were a few missteps during my attempt (at least when transferring to Bluehost).\n\nGet account IP\n\nOn your host (e.g. Bluehost), find out which IP your blog is served from. For Bluehost, this can be found under “Advanced” -&gt; “Server Information” -&gt; “Shared IP Address”. You can also open command prompt and enter ping temporaryblogurl.yourhost.com (using your temporary blog URL of course!) and it should return the IP it is being served from. I didn’t realise this when setting it up, and had to get their (very patient) chat support to help me find it!\n\nSet up CNAME + A record\n\nNow that you have the IP, you can tell Cloudflare (or wherever else your site is hosted) to redirect all blog subdomain requests to it. This is done by adding (or editing) 2 new “A” (alias) records. The first should have a Name of “blog” and an IPv4 address of your IP from earlier. The second should have a Name of “www.blog” and the same IPv4 address again. The “Status” should also be set to DNS only (grey cloud), or you’ll experience redirect issues caused by your host struggling to direct traffic properly. These changes should take effect immediately, but can take a few hours to propagate around various servers on the internet and be properly applied. \n\nChange site URL on BlueHost / your host\n\nNow, your new site needs to know where you just set it up to appear! It needs to know the URL it is appearing at, this ensures all page links go to the correct place and no images / other content is lost. On Bluehost, this option is found under “My Sites”, mouseover your new site then “Manage Site”. Under the “Settings” tab the Site URL can be set to the full URL of your blog. You should also use this opportunity to look at the other settings on this page, and turn off the “Coming Soon Page” to make sure users can actually see your site. \n\nFix URLs\n\nYou may notice that your post’s URLs have changed. My post structure changed from domain.com/year/month/day/post-name to domain.com/post-name. I decided I preferred this change, so updated any internal links to point to the correct URL. I also had Google Search Console enabled, so I was informed of any broken links. To ensure any search results still worked, I used Yoast SEO‘s “Tools” -&gt; “File editor” to redirect all of the old format links to the new format. I did this by adding the following line to the top of my .htaccess file:\nRewriteRule ^([0-9]+)/([0-9]+)/([0-9]+)/(.*)$ /$4 [R=301,NC,L]\n\n\nThere are other tools for editing this file, I just used Yoast because I already had it installed. ### Fix posts\n\nFinally, have a look over your posts, particularly the most complicated ones. Whilst most of the earlier issues should be resolved by the newly installed plugins and fixed URL, minor issues may remain. For example, on my blog the code formatting had broken slightly due to the plugin used, so some of my posts had to be corrected manually.\n\nConclusion\n\nWhilst moving away from the simple and straightforward WordPress.com can be intimidating, the freedom provided by other hosts is easily worth it. Most hosts offer plans similarly priced to the most basic WordPress.com plan, but offer the ability to customise your site as much as you like. The ability to install plugins also means you can set up functionality (for free) like autoposting to social media, improving your SEO, and backing up your site’s posts to another site.\n"
    } ,
  
    {
      "tags"     : "Gutenberg, SNAP, Social Media, Wordpress",
      "title"    : "How To Fix Nextscripts Social Networks Auto-Poster Not Using Correct Categories / Tags",
      "excerpt"  : "This blog uses Nextscript’s SNAP to autopost new posts on LinkedIn, Twitter, and Medium. After installing and activating a few new plugins, I noticed that a scheduled post (“How To View Trello Card Name / Description History”) had been posted with the default category (Android Dev) instead of the correct category (Project Management). Additionally, none of the post’s tags were included in any of the automatic posts.\n",
      "url"      : "/how-to-fix-nextscripts-social-networks-auto-poster-not-using-correct-categories-tags/",
      "date"     : "Oct 31, 2018",
      "content"  : "This blog uses Nextscript’s SNAP to autopost new posts on LinkedIn, Twitter, and Medium. After installing and activating a few new plugins, I noticed that a scheduled post (“How To View Trello Card Name / Description History”) had been posted with the default category (Android Dev) instead of the correct category (Project Management). Additionally, none of the post’s tags were included in any of the automatic posts.\n\n\n\nAfter a little trial and error, I discovered the cause: Gutenberg Editor. Creating any posts in this new editor caused the issue, and just disabling the plugin resolved the issue instantly.\n\nWhilst the plugin was useful, and had a lot of improvements over the default TinyMCE editor, it wasn’t worth ruining all social media posts!\n"
    } ,
  
    {
      "tags"     : "Agile, API, Kanban, Trello",
      "title"    : "How To View Trello Card Name / Description History",
      "excerpt"  : "Trello’s card management system is an extremely widely used approach to managing smaller projects, by moving cards left to right as they progress through various stages (Needs Estimate, In Progress, In QA, etc). Having a history of actions taken is essential, as it ensures all team members are aware of the card’s state at any time.\n",
      "url"      : "/how-to-view-trello-card-name-description-history/",
      "date"     : "Oct 30, 2018",
      "content"  : "Trello’s card management system is an extremely widely used approach to managing smaller projects, by moving cards left to right as they progress through various stages (Needs Estimate, In Progress, In QA, etc). Having a history of actions taken is essential, as it ensures all team members are aware of the card’s state at any time.\n\nThe activity log below each card contains details of the card movements between columns, comments, and assigned members. However, it misses crucial information such as the card’s name and description, which can easily be accidentally edited with no undo option. To access this information, we’ll have to do a (very basic!) dive into Trello’s API…\n\nGet card ID\n\nFirst, open the target card that you need the history for. In the URL, after /c/ there should be an 8 character long card identifier.\nFor example, from the URL https://trello.com/c/utrTeUcA/376-test-card, we can retrieve the ID of utrTeUcA.\n\nCreate base URL\n\nTo access the API, put the ID identified into the following URL: https://trello.com/1/cards/ID HERE/actions. For example, our ID from earlier gives us https://trello.com/1/cards/utrTeUcA/actions.\n\nBy default, this will return a JSON array of all comments on the card, with a large amount of metadata.\n\nFiltering results\n\nFinally, we need to make the results more readable, and retrieve only the changes we’re actually interested in.\n\nTo make it more readable, the extension JSONView will format the returned results in an easily readable format. Once this is installed, it will automatically apply on pages that contain just JSON content, and can be disabled when not needed.\n\nTo display only name changes, add ?filter=updateCard:name to the end of the URL. For description changes, add ?filter=updateCard:description. This will display the new value (under card), and the previous value (under old).\n\n\n\nNote that this data can take a few minutes to be deleted, so for testing this approach it’s best to use an existing card with changes instead of making new changes.\n"
    } ,
  
    {
      "tags"     : "Dependency, Firebase, FirebaseUI",
      "title"    : "TokenRefresher Fatal Crash When Using FirebaseUI",
      "excerpt"  : "FirebaseUI is a very useful collection of UI components for Firebase. It removes some of the complexity of implementing Firebase components by providing ready made UI components that your code can hook into. The FirebaseUI-auth library is used for Firebase Authentication in the Firebase series‘ reference app, as well as various other Firebase dependencies.\n",
      "url"      : "/tokenrefresher-fatal-crash-when-using-firebaseui/",
      "date"     : "Oct 28, 2018",
      "content"  : "FirebaseUI is a very useful collection of UI components for Firebase. It removes some of the complexity of implementing Firebase components by providing ready made UI components that your code can hook into. The FirebaseUI-auth library is used for Firebase Authentication in the Firebase series‘ reference app, as well as various other Firebase dependencies.\n\nHowever, when first running the app, occasionally it would crash with a somewhat cryptic error:\n\n10-24 21:42:00.247 17892-17941/uk.co.jakelee.firebasereference E/AndroidRuntime: FATAL EXCEPTION: TokenRefresher\nProcess: uk.co.jakelee.firebasereference, PID: 17892\njava.lang.NoSuchFieldError: No field PREFER_HIGHEST_OR_REMOTE_VERSION_NO_FORCE_STAGING of type Lcom/google/android/gms/dynamite/DynamiteModule$VersionPolicy; in class Lcom/google/android/gms/dynamite/DynamiteModule; or its superclasses (declaration of 'com.google.android.gms.dynamite.DynamiteModule' appears in /data/app/uk.co.jakelee.firebasereference-2/base.apk:classes3.dex)\n    at com.google.android.gms.flags.FlagValueProvider.initialize(Unknown Source)\n    at com.google.android.gms.flags.FlagRegistry.initialize(Unknown Source)\n    at com.google.firebase.auth.internal.zzx.initialize(Unknown Source)\n    at com.google.firebase.auth.internal.zzt.run(Unknown Source)\n\n\nAfter looking through my commit history, I realised the problem started appearing when I previously attempted to fix a mismatched libraries error:\n\nThe library com.google.android.gms:play-services-basement is being requested by various other libraries at [[15.0.1,15.0.1]], but resolves to 16.0.1. Disable the plugin and check your dependencies tree using ./gradlew :app:dependencies.\n\n\nTo resolve this, I’d added a temporary workaround in my build.gradle, which I completely forget to fix properly:\n\nGoogleServicesPlugin.config.disableVersionCheck = true\n\n\nRemoving this version check disabler, and actually dealing with the root cause (mismatched libraries) led to the realisation that the FirebaseUI auth dependency was using an older version of play-services-basement.\n\nUpdating the com.firebaseui:firebase-ui-auth dependency to 4.2.1 from 4.1.0 fixed the problem instantly. The “quick fix” was no quicker or easier than actually fixing it properly!\n"
    } ,
  
    {
      "tags"     : "Firebase Analytics, Google Analytics, Kotlin, Marketing",
      "title"    : "Centralising Firebase / Google Analytics Screen Tracking Using Android Fragments",
      "excerpt"  : "Whilst tracking user’s screen views with Firebase / Google Analytics can be very simple to setup, it can easily result in a very messy codebase, with hardcoded strings all over the place. Keeping all of the tracking logic in one place allows an instant overview of all tracked screens, as well as easily checking where a screen is reporting a view. Note that this tutorial is for fragments, activities can already be tracked easily automatically.\n",
      "url"      : "/centralising-firebase-google-analytics-screen-tracking-using-android-fragments/",
      "date"     : "Oct 27, 2018",
      "content"  : "Whilst tracking user’s screen views with Firebase / Google Analytics can be very simple to setup, it can easily result in a very messy codebase, with hardcoded strings all over the place. Keeping all of the tracking logic in one place allows an instant overview of all tracked screens, as well as easily checking where a screen is reporting a view. Note that this tutorial is for fragments, activities can already be tracked easily automatically.\n\nThis guide on how to create a TrackingUtil() class is also available as a Gist. It also assumes Analytics has already been setup!\n\nIn our TrackingUtil class, we’re going to achieve two goals. Centralise all screen name definitions, and provide a simple interface to report views via.\n\nCentralised screen name definition\n\nAn enum is perfect for this, as it can easily be referenced in other classes, whilst maintaining a static name without needing to use strings.\n\nclass TrackingUtil(val context: Context) {\n    enum class Screens {\n        ChangePassword,\n        Contact,\n        Dashboard,\n        DashboardInfo,\n        ForgottenPassword,\n        Info,\n        Login,\n        Registration\n    }\n\n\nNow, the login fragment / activity can use TrackingUtil.Login if it wishes to log a screen view.\n\nReporting interface\n\nA simple wrapper will be used for this, without any modification to the incoming screen views. In this example of filtering reported screen views, no data is sent when in debug mode.\n\n    fun track(screen: Screens) {\n        if (!BuildConfig.DEBUG) {\n            FirebaseAnalytics.getInstance(context.applicationContext)\n                .setCurrentScreen(context, screen.name, null)\n            Timber.d(\"Sending screen view of ${screen.name}\")\n        }\n    }\n\n\nAlternatively, user properties can be used to filter environment data.\n\nUsing TrackingUtil\n\nNow, just call .track on an instance of TrackingUtil and pass a screen from our earlier enum to send a screen view. If using fragments, the best place is inside onCreateView:\n\n    override fun onCreateView(\n        inflater: LayoutInflater,\n        container: ViewGroup?,\n        savedInstanceState: Bundle?\n    ): View? {\n        TrackingUtil(activity!!).track(TrackingUtil.Screens.Login)\n        return inflater.inflate(R.layout.fragment_login, container, false)\n    }\n\n\nWhilst this solution does require access to a context, the core Firebase Analytics call does too, so this is no more trouble than using the original reporting method.\n\nPerforming “Find Usages” on any screen in the enum provides a quick way to check the correct places are calling each screen, and any unused screen name will be immediately obvious due to the grey colour caused by an unused resource.\n\nViewing screen view data\n\nOn the main Analytics dashboard, the user engagement widget provides a link to “View screen_view event details”, which will take you to an overview of where users have been in your app.\n\nNext, selecting “Screen name” in the “User engagement” widget will show where users have been in your app, broken down by percentage and average time.\n\n\nThis data on a per-screen basis should help analyse and improve user’s experiences in your app, and tell you the areas people care most about. Even if there is no current goal to track and analyse this data, it’s worth tracking in case it’s needed in the future.\n"
    } ,
  
    {
      "tags"     : "Custom Build Type, Firebase Analytics, Google Analytics, Kotlin, Marketing",
      "title"    : "Filtering Google / Firebase Analytics Traffic By BuildType / Environment On Android",
      "excerpt"  : "Firebase Analytics / Google Analytics is the most widely used service for analysing traffic, and can be used to track detailed information about how users use your app. However, by default it will track all information, including any logged during development or QA. This may mean that the new page you’re working on seems to have a massive spike in traffic, potentially misleading any marketing efforts.\n",
      "url"      : "/filtering-google-firebase-analytics-traffic-by-buildtype-environment-on-android/",
      "date"     : "Oct 26, 2018",
      "content"  : "Firebase Analytics / Google Analytics is the most widely used service for analysing traffic, and can be used to track detailed information about how users use your app. However, by default it will track all information, including any logged during development or QA. This may mean that the new page you’re working on seems to have a massive spike in traffic, potentially misleading any marketing efforts.\n\nWhilst this tutorial covers Firebase Analytics especially, the steps are identical for Google Analytics. Note that only apps added as a “Mobile app” (e.g. using Firebase) can use user properties.\n\nCreating the user property\n\nFirst, go to the “User Properties” link in the sidebar of the Firebase dashboard, and click the “New User Property” button.\n\n\nEnter “Environment” as your user property name, and an optional description, then press “Create”, and your new user property will be in the list. Please note that User Properties cannot be deleted or renamed, so type them carefully!\n![environment]/wp-content/uploads/2018/10/zzqo4b4.png)\n\nSetting the user property\n\nNow the user property has been created, values can be set for it. This tutorial assumes you’ve already added Firebase Analytics for Android.\n\nThe easiest way to do this is to just send the current BuildConfig.BUILD_TYPE, as this ensures any future custom build types (e.g. “QA” or “Preprod”) will be sent automatically. However, custom logic can of course be used instead.\n\nThis should be placed inside the onCreate or onStart of your application, with the rest of your initialisations.\n\nFirebaseAnalytics.getInstance(this)\n    .setUserProperty(\"Environment\", BuildConfig.BUILD_TYPE)\n\n\nFiltering by user property\n\nOnce the app has been run with a user property set, the new value will be automatically added to Analytics to be filtered on. To apply the filter, click the grey dotted “Add Filter” button in the top left of Analytics, select “User Property”, and select the Environment values you’d like to view data for. In the example below, only data from preprod and release environments will be shown, omitting all development or testing data.\n\n\nNow that Analytics data is filtered to only include your real customers, the more accurate representation should help give a better idea of a user’s experience inside your app, and how to improve it.\n"
    } ,
  
    {
      "tags"     : "Firebase, Kotlin, Realtime Database",
      "title"    : "Developing Android Apps With Firebase Realtime Database",
      "excerpt"  : "Firebase Realtime Database is the more traditional predecessor to Firestore, and is essentially a way to store data as JSON and sync it between all clients / servers. Google have also provided a full comparison.\n",
      "url"      : "/developing-android-apps-with-firebase-realtime-database/",
      "date"     : "Oct 25, 2018",
      "content"  : "Firebase Realtime Database is the more traditional predecessor to Firestore, and is essentially a way to store data as JSON and sync it between all clients / servers. Google have also provided a full comparison.\n\nNote that the JSON structured format can be quite limiting, and often requires thinking outside the box to make your existing data format fit inside it.\n\nThis post is part of The Complete Guide to Firebase. Throughout this tutorial, you’ll need access to the Firebase Realtime Database dashboard, and the official documentation may be useful too.\n\nImplementation\n\nAs always, the entire Firebase Reference Project is open source, and there is a pull request for adding Firebase Realtime Database if you just want to see the code changes required.\n\nThis tutorial assumes you already have Firebase added to your project.\n\nSetting up\n\nAs Google recommends Cloud Firestore, it can be a little tricky to actually create the traditional Realtime Database. On the Fireside Database page, scroll down to the Realtime Database banner and select “Create database”.\n\n\nCreate the database in test mode, making sure to set up proper access control later on before the app gets released to a wider audience.\n\nNext, add the dependency to your app-level build.gradle file:\n\nimplementation 'com.google.firebase:firebase-database:16.0.3'\n\n\nThat’s it, it’s implemented!\n\nGetting data\n\nSetting up an automatic data change listener is the most convenient way to be notified on any data changes, including when the activity / fragment starts up. To do this, select the specific node to be monitored, and add a listener. In the following example, the node “nestedData” is used:\n\n     FirebaseDatabase.getInstance().getReference(\"nestedData\").addValueEventListener(object : ValueEventListener {\n            override fun onDataChange(dataSnapshot: DataSnapshot) {\n                displayData(dataSnapshot.value.toString())\n            }\n\n            override fun onCancelled(error: DatabaseError) {\n                showToast(\"Failed to read value: ${error.toException()}\")\n            }\n        })\n\n\nAs all data is stored as a giant JSON object, advanced filtering is not possible. Child nodes can be directly selected, for example .getReference(\"nestedData\").child(\"childNode\"), and there is some limited filtering available (official documentation).\n\nFiltering\n\nA few filtering methods are available, but are limited to selecting the first or last x results, or displaying results where a value is above, below, or equal to a specified value. These can also be combined, the table below explains these further:\n\n\nOrdering\n\nAdditionally, child nodes can be ordered somewhat, by using .orderByKey, .orderByValue, or .orderByChild(\"xyz\"). This can be combined with the previously described filtering methods, but only one ordering technique can be used at once.\n\nInserting data\n\nOne advantage of Realtime Database is it can serialise your objects into JSON for you, keeping all parameter names intact. The examples below use the data class DataRow, a simple class containing just uuid and number:\n\ndata class DataRow(val uuid: String, val number: String)\n\n\nAdditionally, nestedData is the node all operations are performed on, a reference to it is obtained via FirebaseDatabase.getInstance().getReference(\"nestedData\").\n\nAutomatic ID\n\nTo get Firebase to automatically create an ID, .push() to a node, then retrieve the key immediately afterwards. This new child node can then be written to.\n\nval key = nestedData.push().key\nkey?.let {\n    nestedData.child(key).setValue(DataRow(\"thisisauuid\", 1234))\n}\n\n\nThis child node will now be saved under a random ID inside nestedData, with a key similar to “-LPc3jx0y-Hg6aITpvw2”.\n\nManual ID\n\nTo manually set the ID, just write to your desired ID and the node will be created for you. This can be used for multiple levels of nesting to instantly create a multi-node data structure.\n\nnestedData.child(\"collection\").child(\"group\").setValue(DataRow(\"anotheruuid, 4321\"))\n\n\nUpdating data\n\nUpdating data is almost identical to adding new rows, you just need to set the new value of a node. The example below loops through every returned node, retrieves the key, then uses that to get a reference to the updateable node. It then sets the “uuid” value to the current value, except with an asterisk before it.\n\nThe .addListenerForSingleValueEvent() listener is important, as it stops any future data changes (such as the current update!) triggering the listener again.\n\nnestedData.addListenerForSingleValueEvent(object : ValueEventListener {\n        override fun onDataChange(dataSnapshot: DataSnapshot) {\n            for (postSnapshot in dataSnapshot.children) {\n                val child = nestedData.child(postSnapshot.key.toString()).child(\"uuid\")\n                val existingUuid = postSnapshot.child(\"uuid\").value\n                child.setValue(\"*$existingUuid\")\n            }\n        }\n\n\nDeleting data\n\nAgain, deleting data is very similar to updating it. The easiest way to remove data is to simply set it to null. That’s it!\n\nFor example, to wipe everything inside nestedData:\n\nnestedData.setValue(null)\n\n\nWeb interface\n\nThe web interface for Realtime Database allows reading / modifying the stored data, managing access rules, as well as enabling backups and monitoring usage.\n\nData tab\n\nThis tab allows adding, editing, and deleting nodes. It’s also possible to create new nested data, and is a good way to form the basic data structure before beginning programmatically adding data.\n\n\nRules tab\n\nThe rules tab handles security for your database. These aren’t covered in this tutorial, but the official documentation is very comprehensive.\n\nBackups tab\n\nThis tab is only useful on Blaze or above plans, and will allow you to start a manual backup or manage existing automatic backups. These will be compressed using GZip by default.\n\nUsage tab\n\nThis tab provides information on the recent usage of your database. It is updated every minute, and is an excellent way to get a quick overview of system load, and upgrade plans if necessary.\n\n\nConclusion\n\nWhilst Realtime Database’s node based architecture is perfect for some projects, its features pale in comparison to the more modern Cloud Firestore. As such, it’s hard to recommend Realtime Database for any new projects, except those that already have a node-based data structure.\n\nThe offline data caching and syncing between all clients is as powerful as ever, but I find it hard to see any benefits over Firestore.\n\nPrevious: Developing Android Apps With Firebase Cloud Firestore\n\nNext: Developing Android Apps With FIrebase Cloud Functions\n"
    } ,
  
    {
      "tags"     : "Beta, Crashlytics, Custom Flavours, Fabric",
      "title"    : "Using Fabric (Answers / Beta / Crashlytics) With App Flavours",
      "excerpt"  : "Setting up Fabric is usually pretty straightforward, especially as they have a step by step guide, and even an Android Studio plugin that can do it all for you.\n",
      "url"      : "/using-fabric-answers-beta-crashlytics-with-app-flavours/",
      "date"     : "Oct 25, 2018",
      "content"  : "Setting up Fabric is usually pretty straightforward, especially as they have a step by step guide, and even an Android Studio plugin that can do it all for you.\n\nInitialising Fabric is also just a simple one-liner in your application class’ onCreate():\n\nFabric.with(this, new Crashlytics());\n\n\nEasy, run the app and we’re done! Except.. not if we’re using more than one flavour. The package names of the alternate flavours won’t register, uh oh…\n\nSince Fabric automatically picks up the app identifier from the manifest, it isn’t possible to manually add an alternate flavour, and even running the alternate flavour doesn’t force Fabric to add it.\n\nTo get around this, the app identifier has to be manually set when Fabric is initialised, based on the current BuildConfig:\n\nFabric.with(\n    Fabric.Builder(this)\n        .kits(Crashlytics())\n        .appIdentifier(BuildConfig.APPLICATION_ID)\n        .build()\n)\n\n\nNow, the current application ID will be registered, instead of the package used in AndroidManifest.xml. The different flavours will be treated as completely independent apps in Fabric, so will have different crash reports, Beta release groups, etc.\n"
    } ,
  
    {
      "tags"     : "Callback, Interface, Kotlin, Navigation",
      "title"    : "Adding Callbacks From Fragment To Activity Or Activity To Application In Android",
      "excerpt"  : "When navigating between components in your Android app, you’ll sometimes want to call back to the component’s parent. If your navigation uses activities, startActivityForResult() is easy to use and works fine. However, if your app is a more modern app and uses fragments, this won’t work, and there is no startFragmentForResult() function! It can also be helpful for the application class to know the result from a specific activity.\n",
      "url"      : "/adding-callbacks-from-fragment-to-activity-or-activity-to-application-in-android/",
      "date"     : "Oct 24, 2018",
      "content"  : "When navigating between components in your Android app, you’ll sometimes want to call back to the component’s parent. If your navigation uses activities, startActivityForResult() is easy to use and works fine. However, if your app is a more modern app and uses fragments, this won’t work, and there is no startFragmentForResult() function! It can also be helpful for the application class to know the result from a specific activity.\n\nOne solution (among others) to this problem is to define an interface with a callback that the parent component can implement, and the child component can obtain a reference to and then call. If that sounds a little complicated, the code should clarify!\n\nThis post is also available as a Gist.\n\nThe interface\n\nThe interface (I’ve called mine ActionHandler) just needs to define a handleAction function, which takes a single string as a parameter.\n\ninterface ActionHandler {\n    fun handleAction(actionCode: String)\n}\n\n\nThe parent\n\nThe parent activity or application needs to implement ActionHandler (e.g. MainActivity : ActionHandler {) and override handleAction. For example, the activity may need to perform different actions based on which fragment has just been closed.\n\n    override fun handleAction(actionCode: String) {\n        when {\n            actionCode == FragmentA.FRAGMENT_A_CLOSED -&gt; {\n                doSomething()\n            }\n            actionCode == FragmentB.FRAGMENT_B_CLOSED -&gt; {\n                doSomethingElse()\n            }\n            actionCode == FragmentC.FRAGMENT_C_CLOSED -&gt; {\n                doAnotherThing()\n            }\n        }\n    }\n\n\nThe child\n\nThe child fragment or activity needs to have a public constant defined in the companion, used to check which callback is being triggered.\n\n    companion object {\n        const val FRAGMENT_A_CLOSED = \"com.example.fragment_a_closed\"\n    }\n\n\nNow, when the fragment should be closed (e.g. if it’s a modal and the user has pressed the close button), try to call the parent’s callback. It’s worth wrapping this in a try/catch in case the fragment has accidentally been opened from another activity. The parent should never be null, as an activity can’t live without an application, and a fragment can’t live without an activity!\n\n    try {\n        (activity as ActionHandler).handleAction(FRAGMENT_A_CLOSED)\n    } catch (e: ClassCastException) {\n        Timber.e(\"Calling activity can't get callback!\")\n    }\n    dismiss()\n\n\nThat’s it! Now, when the child calls handleAction, the parent will receive the callback, and can perform any action needed.\n\nNext steps\n\nIf additional data should be passed back, an additional parameter can be added to the interface for the child to send back to the parent. The child does not also necessary have to close for the parent to receive the callback, even though receiving a callback on fragment close is the most common use case.\n\nIt’s also worth pointing out that there are many alternative techniques, but I found the method above to be the simplest and cleanest solution, as well as the easiest to add new functionality too.\n"
    } ,
  
    {
      "tags"     : "CI, Custom Flavours, Dependency, Gradle, Notifications, OneSignal",
      "title"    : "Fixing Dependency Conflict In OneSignal Android",
      "excerpt"  : "Whilst following OneSignal’s setup guide for their Android SDK, everything went smoothly until attempting to run the build past our CI (continuous integration) server, CircleCI. I’ve encountered various issues when using custom build flavours with OneSignal before, and expect that was the cause of this issue too.\n",
      "url"      : "/fixing-dependency-conflict-in-onesignal-android/",
      "date"     : "Oct 23, 2018",
      "content"  : "Whilst following OneSignal’s setup guide for their Android SDK, everything went smoothly until attempting to run the build past our CI (continuous integration) server, CircleCI. I’ve encountered various issues when using custom build flavours with OneSignal before, and expect that was the cause of this issue too.\n\nThe build failed, due to the following exception:\n\nExecution failed for task ':app:preCustomflavourQaAndroidTestBuild'.\n&gt; Conflict with dependency 'com.google.firebase:firebase-messaging' in project ':app'. Resolved versions for app (17.0.0) and test app (12.0.1) differ. See https://d.android.com/r/tools/test-apk-dependency-conflicts.html for details.\n\n\nAs Firebase messaging was not used in any modules inside the project, only by OneSignal, the conflict was a little confusing. Was it… conflicting with itself!? Regardless, the solution was relatively straightforward, simply forcing Firebase Messaging to always resolve to the correct version (17.0.0) fixed the test build.\n\nInside the app-level build.gradle, add:\n\nconfigurations.all {\n    resolutionStrategy {\n        force \"com.google.firebase:firebase-messaging:17.0.0\"\n    }\n}\n\n\nThis change fixed the test build, and our CI was back to a lovely sea of green success messages!\n"
    } ,
  
    {
      "tags"     : "Android, Cloud Firestore, Database, Firebase, Kotlin",
      "title"    : "Developing Android Apps With Firebase Cloud Firestore",
      "excerpt"  : "Cloud Firestore provides an app an invisibly syncing cloud database. This takes away a lot of the complexity of ensuring data is up to date, and has very simple methods for creating, retrieving, updating, and deleting data. It also allows syncing between multiple clients, and managing the database via a web interface or an API.\n",
      "url"      : "/developing-android-apps-with-firebase-cloud-firestore/",
      "date"     : "Oct 22, 2018",
      "content"  : "Cloud Firestore provides an app an invisibly syncing cloud database. This takes away a lot of the complexity of ensuring data is up to date, and has very simple methods for creating, retrieving, updating, and deleting data. It also allows syncing between multiple clients, and managing the database via a web interface or an API.\n\nNote that this service is in beta, and is intended to replace the existing Cloud Datastore. Google provides a full comparison to aid in choosing the most appropriate service.\n\nThis post is part of The Complete Guide to Firebase. Throughout this tutorial, you’ll need access to the Firebase Cloud Firestore dashboard, and the official documentation may be useful too.\n\nImplementation\n\nAs always, the entire Firebase Reference Project is open source, and there is a pull request for adding Firebase Cloud Firestore if you just want to see the code changes required.\n\nThis tutorial assumes you already have Firebase added to your project.\n\nSetting up\n\nFirst, open the Database section of the Firebase Console. Whilst the actual database service will be covered in a separate post, this post covers the beta Cloud Firestore. Click the “Create database” button on the banner at the top of the page.\n\n\nIn the dialog that appears, start the database in test mode. This should never be used in production, as it allows anyone to do anything to the database! For early development though, it’s sufficient. A guide is available for configuring these security rules.\n\n\nIt can take 20-30 seconds for the Cloud Firestore database to start up, but once it has you’ll see an empty dashboard, since we’ve currently got no data. That’s it, the database is ready to go, now for the app!\n\n\nIn the app, just add the following dependency to begin using Cloud Firestore:\n\nimplementation 'com.google.firebase:firebase-firestore:17.1.1'\n\n\nFor all of the following examples, db is defined as FirebaseFirestore.getInstance()\n\nGetting data (SELECT)\n\nThere are 2 ways to get data, automatically when it changes or on demand, both will be covered here.\n\nAutomatically retrieving Firestore data\n\nLuckily, setting up a listener for data changes is extremely straightforward, and it provides a querySnapshot with the latest version of all rows. This can be run on any query, but for monitoring all data the following should be used:\n\ndb.collection(tableName).addSnapshotListener { querySnapshot, _ -&gt;\n    displayDocuments(querySnapshot!!.documents)\n}\n\n\nSelectively getting Firestore data\n\nUsing db.collection(\"MyTable\") returns all documents (essentially rows) within in the “MyTable” collection (table).\n\ndb.collection(tableName)\n    .orderBy(\"number\", Query.Direction.DESCENDING)\n    .limit(3)\n    .get()\n    .addOnCompleteListener { task -&gt;\n        if (task.isSuccessful) {\n            displayDocuments(task.result?.documents!!)\n        } else {\n            showToast(\"Error getting documents: ${task.exception}\")\n            tableContents.text = \"\"\n        }\n    }\n\n\nAs with any database, usually when you’re retrieving data it’s going to be with a few criteria, all of which can be combined. For example:\n\n\n  Checking value: .whereLessThan(\"columnName\", 100), .whereEqualTo(\"columnName\", \"value\"), or .whereGreaterThanOrEqualTo(\"columnName\", 100)\n  Limiting results: .limit(5)\n  Ordering: .orderBy(\"total\", Query.Direction.DESCENDING)\n\n\nInserting data (CREATE)\n\nAutomatically setting Firestore ID\n\nCreating a new row / document is extremely easy, and just requires passing a HashMap of columns and values to .add(). Adding listeners is simple too.\n\ndb.collection(tableName)\n    .add(hashMapOf(\n            \"columnA\" to 123,\n            \"columnB\" to \"a value\"\n    ) as Map)\n    .addOnSuccessListener { documentReference -&gt;\n        showToast(\"DocumentSnapshot added with ID: ${documentReference.id}\")\n    }\n    .addOnFailureListener { e -&gt;\n        showToast(\"Error adding document: $e\")\n    }\n\n\nManually setting Firestore ID\n\nWhilst similar to the previous section, manually setting a Firestore ID (primary key) requires looking up the non-existent ID with .document(), then setting it’s values using set().\n\ndb.collection(tableName).document(\"newDocumentID\")\n    .set(hashMapOf(\n            \"columnA\" to 123,\n            \"columnB\" to \"a value\"\n    ) as Map)\n    .addOnSuccessListener {\n        showToast(\"DocumentSnapshot added with ID: $id\")\n    }\n    .addOnFailureListener { e -&gt;\n        showToast(\"Error writing document: $e\")\n    }\n\n\nUpdating data (UPDATE)\n\nUpdating rows is very straightforward, once a reference to a row is obtained .set() will do all the work of synchronising changes and resolving any conflicts.\n\nThe following snippets assumes it.id is a document reference, and updates “columnName” to “1234”:\n\nval ref = db.collection(tableName).document(it.id)\nit.data?.let {\n    ref.update(\"columnName\", 1234)\n}\n\n\nDeleting data (DELETE)\n\nSimilarly to updating data, deleting data just requires calling .delete() on the document reference.\n\nval ref = db.collection(tableName).document(it.id)\nref.delete()\n\n\nWeb interface\n\nData tab\n\nThe Cloud Firestore web interface’s data tab is a convenient way of viewing all data in the database. All collections (tables), documents (rows), and fields can be added, edited, or deleted directly. This can be extremely beneficial when attempting to debug a data issue, as it allows diagnosing the issue from any device.\n\nIn addition to viewing all data, rows can be filtered using the standard selection criteria, and sorted.\n\n\nRules tab\n\nThe rules tab is worth visiting before publishing any app using Cloud Firestore. Similar to routing tables in a normal server, these rules can be used to configure who can read and write what data. For example, users may be able to edit fields in their row, but not in anybody else’s. Assuming the configuration is still set to “Test” from earlier, Firestore will helpfully warn you that the configuration is a massive security risk.\n\nThe existing documentation for Firestore rules is extremely comprehensive, and the ability to simulate all requests (even with fake user authentication) helps ensure access control is correctly setup.\n\n\nIndexes tab\n\nCloud Firestore automatically creates indexes for you, and this is usually enough to ensure solid performance. However, advanced users may wish to add custom indexes. All of these manually added indexes will be displayed here, and can be edited.\n\nUsage tab\n\nThe usage tab just provides a link to Google Cloud Platform, which reveals Cloud Firestore’s very generous usage limits. The table below shows the capacity provided for free, which should be enough for smaller apps.\n\n\nNote that there are also reasonable limits on data stored, writes, indexes, and security rules. A project’s current quota can be viewed on Google Cloud Platform.\n\nConclusion\n\nWhilst it can be a little bit scary giving up control over data persistence, syncing, and access control to a cloud-based service instead of a more typical server, it has a lot of advantages. The costs can be dramatically lower, and the setup time is next to zero. In addition, it offers more reliable scalability than Firebase’s existing Datastore product, and faster feature innovation, at the cost of lacking the normal, non-beta database’s proven history. Finally, the extreme ease of hooking into other Firebase services (whilst still being able to delegate to a traditional server where necessary) makes it a very attractive offering for new systems.\n\nAnother overview of Firebase Cloud Firestore is available by @mono0926 on Medium, and an excellently in-depth look at querying Cloud Firestore has been written by Peter Ekene Eze on DZone.\n\nPrevious: Developing Android Apps With Firebase Authentication\nNext: Developing Android Apps With Firebase Realtime Database\n"
    } ,
  
    {
      "tags"     : "Drawable, Resize, Styles, Vector",
      "title"    : "Reducing The Size Of TextView DrawableStart / DrawableEnds Using Styles",
      "excerpt"  : "Using image files or SVGs at the start / end of a TextView can be an easy way to add icons to menu items, or indicators that clicking the TextView will trigger an action. That being said, it can be tricky to position the drawable correctly, and it may not be possible to easily resize it (especially if it was created by someone else).\n",
      "url"      : "/reducing-the-size-of-textview-drawablestart-drawableends-using-styles/",
      "date"     : "Oct 17, 2018",
      "content"  : "Using image files or SVGs at the start / end of a TextView can be an easy way to add icons to menu items, or indicators that clicking the TextView will trigger an action. That being said, it can be tricky to position the drawable correctly, and it may not be possible to easily resize it (especially if it was created by someone else).\n\nLuckily, there is a partial workaround.\n\nImplementation\n\nScaling the entire TextView smaller will decrease the size of both the text and the drawable, however the text size can then be increased to counteract this change. For example, a text size of 16 is equal to a text size of 20, when scaled to 0.8 (80%). This is because 20 = 16 / 0.8.\n\nThis super simple formula can be expressed as:\n\nnewTextSize = originalTextSize / scale\n\n\nExample\n\nThe image below shows a TextView with text size 16, modified using styles to have a larger and smaller drawableEnd than default:\n\n\nThis was created by extracting the scaling to 3 self explanatory styles, used to scale the drawableEnd to 1.6x and 0.8x original size:\n\n&lt;style name=\"Larger_Drawable\"&gt;\n    &lt;item name=\"android:textSize\"&gt;10sp&lt;/item&gt;\n    &lt;item name=\"android:scaleX\"&gt;1.6&lt;/item&gt;\n    &lt;item name=\"android:scaleY\"&gt;1.6&lt;/item&gt;\n&lt;/style&gt;\n\n&lt;style name=\"Normal_Drawable\"&gt;\n    &lt;item name=\"android:textSize\"&gt;16sp&lt;/item&gt;\n&lt;/style&gt;\n\n&lt;style name=\"Smaller_Drawable\"&gt;\n    &lt;item name=\"android:textSize\"&gt;20sp&lt;/item&gt;\n    &lt;item name=\"android:scaleX\"&gt;0.8&lt;/item&gt;\n    &lt;item name=\"android:scaleY\"&gt;0.8&lt;/item&gt;\n&lt;/style&gt;\n\n\nIn case it helps, the exact layout xml used is similarly self explanatory:\n\n&lt;TextView\n    android:layout_width=\"wrap_content\"\n    android:layout_height=\"wrap_content\"\n    android:text=\"Large\"\n    android:layout_margin=\"10dp\"\n    android:drawableEnd=\"@drawable/ic_smiley\"\n    style=\"@style/Larger_Drawable\"/&gt;\n\n&lt;TextView\n    android:layout_width=\"wrap_content\"\n    android:layout_height=\"wrap_content\"\n    android:text=\"Normal\"\n    android:layout_margin=\"10dp\"\n    android:drawableEnd=\"@drawable/ic_smiley\"\n    style=\"@style/Normal_Drawable\"/&gt;\n\n&lt;TextView\n    android:layout_width=\"wrap_content\"\n    android:layout_height=\"wrap_content\"\n    android:text=\"Small\"\n    android:layout_margin=\"10dp\"\n    android:drawableEnd=\"@drawable/ic_smiley\"\n    style=\"@style/Smaller_Drawable\"/&gt;\n\n\nConclusion\n\nWhile this workaround does work, it definitely isn’t ideal! If at all possible, the original drawable should be resized to fit in the target area. That being said, the example above is relatively clean, allowing a style to resize the drawable instead of multiple modifiers.\n"
    } ,
  
    {
      "tags"     : "BroadcastReceiver, PowerSaving",
      "title"    : "Displaying a \"Power Saving Enabled\" Bar Inside Your Android App",
      "excerpt"  : "If your app uses Android hardware features or otherwise needs to be running most of the time, tools such as power saving mode can limit your app’s freedom. Whilst the mode is great for users, the inconsistent implementation (much better now that Doze mode exists, and power saving is more standardised) often leads to unreliable performance on certain devices. Making users aware of this can prevent giving users a negative impression of your app.\n",
      "url"      : "/displaying-a-power-saving-enabled-bar-inside-your-android-app/",
      "date"     : "Oct 16, 2018",
      "content"  : "If your app uses Android hardware features or otherwise needs to be running most of the time, tools such as power saving mode can limit your app’s freedom. Whilst the mode is great for users, the inconsistent implementation (much better now that Doze mode exists, and power saving is more standardised) often leads to unreliable performance on certain devices. Making users aware of this can prevent giving users a negative impression of your app.\n\nIn this tutorial, a simple animated “Power saving mode enabled” bar will be displayed inside the app whilst there any power saving mode is enabled, and disappear when it is disabled. An example power saving bar project is available, as well as a video of the finished implementation.\n\nPlease note that this only works on Lollipop and above, the APIs needed to safely get power saving status are not available before then.\n\nThis tutorial also shares most of it’s code with an earlier post about displaying a “No Internet” bar in a similar way.\n\nAdd bar to layout\n\nFirst, the bar has to actually be added to the layout. This can of course be customised easily, the demo project uses a bright orange bar to alert the user.\n\n&lt;TextView\n    android:id=\"@+id/power_saving_bar\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"wrap_content\"\n    android:background=\"#F28200\"\n    android:gravity=\"center_horizontal\"\n    android:padding=\"5dp\"\n    android:text=\"Power saving mode is on, this app's super duper features may not work correctly!\"\n    android:textColor=\"#FFFFFF\"\n    android:visibility=\"gone\"\n    app:layout_constraintBottom_toBottomOf=\"parent\" /&gt;\n\n\nSetup power saving listener\n\nNext, a BroadcastReceiver needs to be created to catch the power saving toggle events broadcast by the operating system. The IntentFilter ensures that only the correct events are received.\n\n@RequiresApi(Build.VERSION_CODES.LOLLIPOP)\nprivate fun setupPowerSavingReceiver() {\n    togglePowerSavingBar((getSystemService(Context.POWER_SERVICE) as PowerManager).isPowerSaveMode)\n    powerSavingReceiver = object : BroadcastReceiver() {\n        override fun onReceive(context: Context, intent: Intent) {\n            val powerManager: PowerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager\n            togglePowerSavingBar(powerManager.isPowerSaveMode)\n            Log.e(\"PowerSaving\", \"Enabled: ${powerManager.isPowerSaveMode}\")\n        }\n    }\n    registerReceiver(\n        powerSavingReceiver,\n        IntentFilter(\"android.os.action.POWER_SAVE_MODE_CHANGED\")\n    )\n}\n\n\nHook into Android lifecycle events\n\nNext, we need to make sure receivers are only registered whilst our activity is, otherwise we may continue listening to power saving events even after the app is closed. onStart and onStop should be used for registering and unregistering the receiver.\n\nprivate var powerSavingReceiver: BroadcastReceiver? = null\n\noverride fun onStart() {\n    super.onStart()\n    if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.LOLLIPOP) {\n        setupPowerSavingReceiver()\n    }\n}\n\noverride fun onStop() {\n    super.onStop()\n    powerSavingReceiver?.let { unregisterReceiver(it) }\n}\n\n\nDisplay bar\n\nFinally, and most importantly, we need to actually show the bar! togglePowerSavingMode is called when the power saving mode is enabled or disabled, and accepts a boolean determining if the bar should be shown or hidden. Two simple animations are used to improve appearances:\n\n\n  enter_from_bottom.xml is used for the bar appearing:\n     &lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n &lt;set xmlns:android=\"http://schemas.android.com/apk/res/android\"\n     android:shareInterpolator=\"false\"&gt;\n     &lt;translate\n         android:duration=\"400\"\n         android:fromXDelta=\"0%\"\n         android:fromYDelta=\"100%\"\n         android:toXDelta=\"0%\"\n         android:toYDelta=\"0%\" /&gt;\n &lt;/set&gt;\n    \n  \n  exit_to_bottom.xml is used for the bar disappearing:\n     &lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n &lt;set xmlns:android=\"http://schemas.android.com/apk/res/android\"\n     android:shareInterpolator=\"false\"&gt;\n     &lt;translate\n         android:duration=\"400\"\n         android:fromXDelta=\"0%\"\n         android:fromYDelta=\"0%\"\n         android:toXDelta=\"0%\"\n         android:toYDelta=\"100%\" /&gt;\n &lt;/set&gt;\n    \n  \n\n\nFinally, these animations are used to toggle visibility:\n\nprivate fun togglePowerSavingBar(display: Boolean) {\n    if (display &amp;&amp; power_saving_bar.visibility != View.VISIBLE) {\n        val enterAnim = AnimationUtils.loadAnimation(this, R.anim.enter_from_bottom)\n        power_saving_bar.startAnimation(enterAnim)\n    } else if (!display &amp;&amp; power_saving_bar.visibility != View.GONE) {\n        val exitAnim = AnimationUtils.loadAnimation(this, R.anim.exit_to_bottom)\n        power_saving_bar.startAnimation(exitAnim)\n    }\n    power_saving_bar.visibility = if (display) View.VISIBLE else View.GONE\n}\n\n\nConclusion\n\nThe main drawback of this simple solution is the requirement for Android Lollipop. Luckily, on older devices the functionality simply won’t be enabled, so users won’t actually be aware they are missing out.\n\nAdditionally, during testing I discovered Sony’s “STAMINA MODE” isn’t implemented in the same standardised way as other manufacturers, meaning it cannot be listened to in the same way. A partial workaround is available, by checking Sony device’s settings when the app starts (or onResume):\n\nprivate fun performSonyPowerSavingCheck() {\n    if (Build.MANUFACTURER.toUpperCase() == \"SONY\") {\n        togglePowerSavingBar(\n            Settings.Secure.getInt(contentResolver, \"somc.stamina_mode\", 0) == 1\n        )\n    }\n}\n\n\nThis workaround isn’t perfect, as it only tells you if the user has STAMINA MODE enabled, not whether it is currently active. For example, the user may have it set to activate at 20% battery, and currently be at 100%, yet the check will still return true. As such, consider whether it is worth implementing for Sony devices.\n\nAn example power saving bar project has also been created for this tutorial.\n"
    } ,
  
    {
      "tags"     : "BroadcastReceiver, Connectivity, No Internet",
      "title"    : "Displaying a \"No Internet\" Bar Inside Your Android App",
      "excerpt"  : "Whilst developing an app, you’re likely to have a strong, reliable data connection at all times. In the real world however, users often will be without connectivity, and your app should react appropriately.\n",
      "url"      : "/displaying-a-no-internet-bar-inside-your-android-app/",
      "date"     : "Oct 15, 2018",
      "content"  : "Whilst developing an app, you’re likely to have a strong, reliable data connection at all times. In the real world however, users often will be without connectivity, and your app should react appropriately.\n\nIn this tutorial, a simple animated “No internet is available” bar will be displayed inside the app whilst there is no internet, and disappear when connectivity returns. An example no internet bar project is available, as well as a video of the finished implementation.\n\nAdd network state permission\n\nFirst, permission to access the network state is needed. This permission doesn’t need to be requested at runtime, and just being included in the AndroidManifest.xml is sufficient:\n\n&lt;uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" /&gt;\n\n\nAdd bar to layout\n\nNext, the bar has to actually be added to the layout. This can of course be customised easily, I’ve gone for a solid bright pink bar to grab attention!\n\n    &lt;TextView\n        android:id=\"@+id/no_internet_bar\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:background=\"#FF4081\"\n        android:gravity=\"center_horizontal\"\n        android:padding=\"5dp\"\n        android:text=\"There is no internet connection available!\"\n        android:textColor=\"#FFFFFF\"\n        android:visibility=\"gone\"\n        app:layout_constraintBottom_toBottomOf=\"parent\" /&gt;\n\n\nCreate network receiver\n\nNetworkReceiver.kt is a small class that serves 3 functions:\n\n\n  Checking the current internet status on demand:\n         private fun hasInternet(context: Context): Boolean {\n         val connectMgr = (context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager)\n         val activeNetworkInfo = connectMgr.activeNetworkInfo\n         return activeNetworkInfo != null &amp;amp;amp;&amp;amp;amp; activeNetworkInfo.isConnected\n     }\n    \n  \n  Providing an interface for activities to implement, so that it can broadcast network state change events:\n         interface NetworkReceiverListener {\n         fun onNetworkConnectionChanged(isConnected: Boolean)\n     }\n    \n     companion object {\n         var networkReceiverListener: NetworkReceiverListener? = null\n     }\n    \n  \n  Actually broadcasting the events as they are received:\n         override fun onReceive(context: Context, arg1: Intent) {\n         if (networkReceiverListener != null) {\n             networkReceiverListener!!.onNetworkConnectionChanged(hasInternet(context))\n         }\n     }\n    \n  \n\n\nSetup network listener\n\nInitialising the NetworkReceiver‘s networkReceiverListener hooks the activity into the broadcast receiver we just created. This should be done during onCreate() or as early as possible:\n\n    override fun onCreate(savedInstanceState: Bundle?) {\n        super.onCreate(savedInstanceState)\n        setContentView(R.layout.activity_main)\n        setupNetworkListener()\n    }\n\n    private fun setupNetworkListener() {\n        NetworkReceiver.networkReceiverListener = object : NetworkReceiver.NetworkReceiverListener {\n            override fun onNetworkConnectionChanged(isConnected: Boolean) {\n                toggleNoInternetBar(!isConnected)\n            }\n        }\n    }\n\n\nHook into Android lifecycle events\n\nNext, we need to make sure receivers are only registered whilst our activity is, otherwise we may continue listening to network events even after the app is closed. onStart and onStop should be used for registering and unregistering the receiver.\n\n    private var networkReceiver: NetworkReceiver? = null\n\n    override fun onStart() {\n        super.onStart()\n        networkReceiver = NetworkReceiver()\n        registerReceiver(networkReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))\n    }\n\n    override fun onStop() {\n        super.onStop()\n        networkReceiver?.let { unregisterReceiver(it) }\n    }\n\n\nDisplay bar\n\nFinally, and most importantly, we need to actually show the bar! toggleNoInternetBar is called when the network state changes, and accepts a boolean determining if the bar should be shown or hidden. Two simple animations are used to improve appearances:\n\n\n  enter_from_bottom.xml is used for the bar appearing:\n     &lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n &lt;set xmlns:android=\"http://schemas.android.com/apk/res/android\"\n     android:shareInterpolator=\"false\"&gt;\n     &lt;translate\n         android:duration=\"400\"\n         android:fromXDelta=\"0%\"\n         android:fromYDelta=\"100%\"\n         android:toXDelta=\"0%\"\n         android:toYDelta=\"0%\" /&gt;\n &lt;/set&gt;\n    \n  \n  exit_to_bottom.xml is used for the bar disappearing:\n        \n &lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n &lt;set xmlns:android=\"http://schemas.android.com/apk/res/android\"\n     android:shareInterpolator=\"false\"&gt;\n     &lt;translate\n         android:duration=\"400\"\n         android:fromXDelta=\"0%\"\n         android:fromYDelta=\"0%\"\n         android:toXDelta=\"0%\"\n         android:toYDelta=\"100%\" /&gt;\n &lt;/set&gt;\n    \n  \n\n\nFinally, these animations are used to toggle visibility:\n\n    private fun toggleNoInternetBar(display: Boolean) {\n        if (display) {\n            val enterAnim = AnimationUtils.loadAnimation(this, R.anim.enter_from_bottom)\n            no_internet_bar.startAnimation(enterAnim)\n        } else {\n            val exitAnim = AnimationUtils.loadAnimation(this, R.anim.exit_to_bottom)\n            no_internet_bar.startAnimation(exitAnim)\n        }\n        no_internet_bar.visibility = if (display) View.VISIBLE else View.GONE\n    }\n\n\nConclusion\n\nFor an internet-dependent app, the ability to show users a warning that the displayed data may not be up to date is an easy way to improve the user experience. Small features like this really add up, and can help persuade a user to feel positively towards your app / service.\n\nOne potentially unexpected quirk of the implementation in this tutorial that can cause issues during testing is the delay when disabling Airplane Mode. Once Airplane Mode is disabled, it can take 5-10 seconds until connectivity returns and the bar disappears.\n\nAn example no internet bar project has also been created for this tutorial.\n"
    } ,
  
    {
      "tags"     : "Cracking, Hashcat, Keystore",
      "title"    : "Brute Forcing A Forgotten Keystore Password Using Hashcat",
      "excerpt"  : "Recently, I was preparing an update to a long abandoned Android app of mine when I realised the password to the keystore was long forgotten. A keystore and associated password is essential for updating an app (more information on keystores is available in easy to understand LEGO form), and as such the app could never be updated again!\n",
      "url"      : "/brute-forcing-a-forgotten-keystore-password-using-hashcat/",
      "date"     : "Sep 29, 2018",
      "content"  : "Recently, I was preparing an update to a long abandoned Android app of mine when I realised the password to the keystore was long forgotten. A keystore and associated password is essential for updating an app (more information on keystores is available in easy to understand LEGO form), and as such the app could never be updated again!\n\nLuckily, it’s possible to crack the password to a keystore.\n\nFor this tutorial, the debug keystore will be used, but the steps are exactly the same for a release keystore, i.e. one used to update an app in the store. The debug keystore is located at C:\\Users\\yourusername\\.android\\debug.keystore.\n\nRetrieving hash\n\nTo retrieve the keystore’s hash so it can be cracked, we are going to use a useful little 10KB utility called JksPrivkPrepare.jar.\n\n\n  First, download floyd-fuh’s hash retriever (source code).\n  Unzip the JKS-private-key-cracker-hashcat-master.zip archive just downloaded.\n  Paste your target keystore inside the unzipped folder (in the same folder as the README.md etc).\n  Open up a command prompt / PowerShell prompt. Pressing shift + right click within the unzipped folder should provide an option to “Open Command Prompt here” or “Open PowerShell window here”.\n  Paste (right click -&gt; paste) the following, replacing debug.keystore with your keystore’s name: java -jar JksPrivkPrepare.jar debug.keystore &gt; hash.txt, then press enter.\n  A hash.txt should now exist in the folder, that’s the hash we need! The tool will also tell you your key’s alias, shown below:\n\n\n\n\nPreparing the hash\n\nOn Windows machines, hash.txt is output in a slightly incorrect format (contains a BOM, which files on Windows shouldn’t have). The easiest solution is to open hash.txt in Notepad++, convert it, then resave it.\n\n\nCracking the hash\n\n\n  First, download Hashcat by clicking “Download” on the “hashcat binaries” row.\n  Unzip the archive (this may require 7zip).\n  Move the fixed hash.txt from earlier into the unzipped folder.\n  Run .\\hashcat -m 15500 -a 3 -1 '?l' -w 3 hash.txt ?1?1?1?1?1?1?1. (more detail on this command in the next section)\n  After a few seconds, you should see the very long hash we retrieved earlier followed by :android, telling us that the cracked password is “android”!\n\n\n\n\nFurther crack configuration\n\nThe command entered earlier, .\\hashcat64 -m 15500 -a 3 -1 '?l' -w 3 hash.txt ?1?1?1?1?1?1? is pretty overwhelming at first glance, but each section can be understood individually. A full list of Hashcat parameters is available, the following settings are sufficient for this purpose however. All reference tables below come from the official documentation.\n\n\n  .\\hashcat: Tells Windows we’re trying to use hashcat.exe.\n  -m 15500: Sets the hash type to “JKS Java Key Store Private Keys (SHA1)”, so that hashes can be compared.\n  -a 3: Sets the attack mode to “Brute-force”, e.g. trying every possible password until the correct one is found.\n\n\n\n\n\n  -1 ‘?l’: Sets the first character set to l for lowercase. A password with uppercase + lowercase letters as well as numbers would need ?u?l?d.\n\n\n\n\n\n  -w 3: Sets the workload profile (intensity) to “High”.\n\n\n\n\n\n  hash.txt: Defines the list of hashes to crack, our file only has one.\n  ?1?1?1?1?1?1?: This sets the “mask” used for the search. Each instance of ?1 refers to the character set we defined earlier, and says there is a character from that character set in that position. We repeat this 7 times since it’s a 7 letter password, usually you would try 5 characters, then 6, etc.\n\n\nThe ability to set multiple character sets in the mask allows for situations where you know the password is a letter followed by numbers, or another pattern.\n\nConclusion\n\nThe bulk of the work in this post is done by Hashcat, an extremely powerful hash cracking tool that has been around for years and is used by everyone from penetration testers to malicious hackers. That being said, it is simply a useful tool, not at all illegal!\n\nPassword cracking can be extremely complicated, but due to Hashcat’s popularity there are thousands of guides online. Alternatively, the official forums can generally help out.\n\nPS: Obviously, I don’t condone cracking any keystores that aren’t your own!\n"
    } ,
  
    {
      "tags"     : "Authentication, Firebase, Kotlin, Tutorial",
      "title"    : "Developing Android Apps With Firebase Authentication",
      "excerpt"  : "Firebase Authentication provides an app with the ability to handle user registration, user logging in, and retrieving user data. It has the ability to integrate with phone-based authentication as well as common services such as Facebook, Twitter, and Github. This tutorial will cover the simplest integrations, email and Google account.\n",
      "url"      : "/developing-android-apps-with-firebase-authentication/",
      "date"     : "Sep 29, 2018",
      "content"  : "Firebase Authentication provides an app with the ability to handle user registration, user logging in, and retrieving user data. It has the ability to integrate with phone-based authentication as well as common services such as Facebook, Twitter, and Github. This tutorial will cover the simplest integrations, email and Google account.\n\nThis post is part of The Complete Guide to Firebase. Throughout this tutorial, you’ll need access to the Firebase Authentication dashboard, and the official documentation may be useful too.\n\nImplementation\n\nAs always, the entire Firebase Reference Project is open source, and there is a pull request for adding Firebase Authentication if you just want to see the code changes required.\n\nThis tutorial assumes you already have Firebase added to your project.\n\nAdding dependencies\n\nTo add Firebase Authentication, only the Auth library is needed in your app-level build.gradle file:\n\nimplementation 'com.firebaseui:firebase-ui-auth:4.1.0'\n\n\nEnabling sign-in methods\n\nNext, the required sign in methods need to be activated in the console. For each, click the relevant row then toggle “Enable”, whilst leaving the other settings as default.\n\nEmail\n\nThe first, email, is very simple. No extra work is required, and it also allows the user to set a password to log back into their account later.\n\nGoogle\n\nThe second, Google account, requires some more work. The SHA-1 fingerprint of your keystore (used to verify a version of your app is legitimate) needs to be added to your Settings page. With your settings page open, a SHA-1 fingerprint can be added by pressing “Add Fingerprint”. This should be done for both debug and release keystores, so that Firebase Auth works in development and when released.\n\nA full guide to generating a SHA-1 fingerprint is provided by Google.\n\nEventually, your settings page should look like the image below. If the SHA-1 fingerprints have not been added correctly, you will see error code 16 when attempting to use Google-based login.\n\n\nYour Firebase project is now ready to receive authentication requests from your app, time to add them!\n\nSigning in\n\nSigning in just requires setting the login methods desired (called providers), and starting Firebase Auth’s login activity along with a request code. Once the sign-in attempt is completed (successfully or unsuccessfully), onActivityResult will be called. The following function can be called when a login button is pressed.\n\n    private fun clickLogin() = startActivityForResult(\n            AuthUI.getInstance()\n                    .createSignInIntentBuilder()\n                    .setAvailableProviders(listOf(\n                            AuthUI.IdpConfig.EmailBuilder().build(),\n                            AuthUI.IdpConfig.GoogleBuilder().build()))\n                    .build(), REQUEST_CODE)\n\n\nCustomisation\n\nThe login experience can be customised to better fit your app. By default your app’s default theme is used, but a custom theme can be set using setTheme() on the SignInIntentBuilder. Additionally, calling setLogo() allows a drawable (e.g. your app’s logo) to be shown in the middle of the screen. Finally, custom Terms of Service and Privacy Policy links can be added using setTosAndPrivacyPolicyUrls(). The following snippet functions identically to that above, but is much more customised:\n\n    private fun clickCustomLogin() = startActivityForResult(\n            AuthUI.getInstance()\n                    .createSignInIntentBuilder()\n                    .setAvailableProviders(listOf(\n                            AuthUI.IdpConfig.EmailBuilder().build(),\n                            AuthUI.IdpConfig.GoogleBuilder().build()))\n                    .setLogo(R.drawable.ic_firebase)\n                    .setTheme(R.style.AuthenticationCustomTheme)\n                    .setTosAndPrivacyPolicyUrls(\n                            \"https://google.com\",\n                            \"https://firebase.google.com\")\n                    .build(), REQUEST_CODE)\n\n\nValidating login\n\nOnce onActivityResult is called, the result needs to be checked to ensure it:\n\n\n  Is the result of the Firebase Auth sign-in\n  Was successful\n\n\nThis can be done by ignoring other requests (by returning early), and checking the result code:\n\n   override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {\n        super.onActivityResult(requestCode, resultCode, data)\n        if (requestCode != REQUEST_CODE) return\n        if (resultCode == RESULT_OK) {\n\n\nAlternatively, if the resultCode is not RESULT_OK, we can try and retrieve a useful error message from the data returned by Firebase, then display it to the user:\n\n       } else {\n            IdpResponse.fromResultIntent(data)?.let {\n                val errorCode = it.error?.errorCode\n                val errorMessage = it.error?.localizedMessage\n                Toast.makeText(activity, String.format(getString(R.string.authentication_login_error), errorCode, errorMessage), Toast.LENGTH_SHORT).show()\n            }\n\n\nGet user information\n\nNow that login has been successful, we can lookup the current user in Firebase using val user = FirebaseAuth.getInstance().currentUser and start extracting data. The unix timestamp for app account created (creationTimestamp) and last sign in (lastSignInTimestamp) are stored in user.metadata.\n\nMost of the useful information is stored within the user.providerData; an array of every service the user has authenticated to your app with. This will usually only have 1 service in it, and the data available does vary by provider. That being said, the following should usually be available on each provider:\n\n\n  providerId: The provider’s name, e.g. “firebase”.\n  uid: The user’s ID for that provider, format varies between provider.\n  displayName: The name the user has chosen on that provider.\n  email: The email the user signed up to the provider with.\n  photoUrl: A publicly accessible image URL containing the user’s profile picture for that provider.\n\n\nThis data is shown in the reference app:\n\n\nSigning out\n\nSigning the user out is even easier than logging in, as the callback is included, instead of requiring a separate function:\n\n   private fun clickLogout() =\n            AuthUI.getInstance()\n                    .signOut(activity!!)\n                    .addOnCompleteListener {\n                        Toast.makeText(activity!!, getString(R.string.authentication_logged_out), Toast.LENGTH_SHORT).show()\n                    }\n\n\nWeb interface\n\nThe web interface consists of 4 tabs for Authentication, as follows:\n\nUsers\n\nThis tab provides a list of all users signed up for your app, and allows searching for specific users and resetting their password or deleting / disabling their account.\n\n\nSign-in method\n\nThis tab consists of general options relating to signing in:\n\n\n  Authorised domains: A list of domains permitted to use OAuth redirects. This should not need to be modified.\n  One account per email address: An option controlling whether the same email address at multiple providers should be merged into one account or not. On by default.\n  Manage sign-up quota: By default, the same IP can register 100 accounts per hour. This can be increased or decreased if necessary.\n  Sign-in providers: A list of all potential sign-in providers (shown below), as well as guidance on how to configure them.\n\n\n\n\nTemplates\n\nThis tab enables customisation of various customer communications, such as the email verification email, SMS verification text, and the ability to use a custom mail server for all emails.\n\nUsage\n\nThis tab outlines the amount of phone verifications used in the current month. US &amp; Canada &amp; India are allowed 10k combined total, and the rest of the world is also allowed 10k combined total.\n\nConclusion\n\nOverall, Firebase Authentication is extremely easy to use, whilst still providing very advanced functionality. It is completely free, and the only limitation is the number of phone authentications permitted per month.\n\nFor many apps, the system will easily be enough to manage all user account needs, with or without an additional server behind it. For more advanced solutions, a custom authentication can be configured, or even anonymous logins. These usually extremely complicated functionalities are reduced to a few lines of code with Firebase, making it a serious contender for any new major app development.\n\nPrevious: Adding Firebase to an Android Project\nNext: Developing Android Apps With Firebase Cloud Firestore\n"
    } ,
  
    {
      "tags"     : "Firebase, Tutorial",
      "title"    : "Adding Firebase to an Android Project",
      "excerpt"  : "Considering the vast array of features included in Firebase, adding it to your project is surprisingly easy. Later versions of Android Studio even include an assistant that analyses the current project and provides fixes for common integration mistakes.\n",
      "url"      : "/adding-firebase-to-an-android-project/",
      "date"     : "Sep 27, 2018",
      "content"  : "Considering the vast array of features included in Firebase, adding it to your project is surprisingly easy. Later versions of Android Studio even include an assistant that analyses the current project and provides fixes for common integration mistakes.\n\nThis guide however, will focus on the very straightforward steps required to integrate Firebase manually.\n\nPrerequisites\n\n\n  An existing Firebase project\n  An existing Android Studio project (an example project is available)\n\n\nGoogle Services file\n\nThe next step is obtaining a google-services.json file, so that the app knows which Firebase project to talk to. This can be done by visiting the project overview and clicking the Android icon.\n\n\nThis will bring up the “Add Firebase” wizard:\n\n\n\n  Android package name: The only required part of this form, this is the package name used when creating your app. It will be visible in the AndroidManifest.xml file as package=\"com.example.test\".\n  App nickname: This is an optional “friendly” name you can use to better summarise the app.\n  Debug signing certificate: This is not needed for most aspects of Firebase, but a guide does exist.\n\n\nOnce 1-3 of the fields have been filled in, the app can now be registered (4). Clicking this button will provide a download link for your google-services.json file, as well as instructions on where to put it. Switch to “Project” view in the left Android Studio sidebar, then put the downloaded file inside the “app” folder.\n\nFirebase SDK\n\nNext, the Firebase library needs to be added to your project. Doing this is just 4 simple steps:\n\n\n  Add classpath 'com.google.gms:google-services:4.0.1' inside the dependencies section of your project level build.gradle (file will have “(Project: yourappname)” next to it).\n  Add implementation 'com.google.firebase:firebase-core:16.0.3' inside the dependencies section of your app level build.gradle (file will have “(Module: app)” next to it).\n  Also add apply plugin: 'com.google.gms.google-services' to the bottom of the app level build.gradle.\n  Finally, press “Sync now” in the yellow bar at the top.\n\n\nNote: As of writing, 16.0.3 is the latest Firebase version, and 4.0.1 the latest Google services version. If these are outdated, Android Studio will prompt you to update.\n\nFinal steps\n\nFinally, just run your app, and the “Add Firebase” wizard will confirm Firebase has been set up correctly:\n\n\nThat’s it, Firebase is fully set up! Your project settings (e.g. name) can be changed later if necessary.\n\nPrevious: Creating A New Firebase Project\nNext: Developing Android Apps With Firebase Authentication\n"
    } ,
  
    {
      "tags"     : "Firebase, Tutorial",
      "title"    : "Creating A New Firebase Project",
      "excerpt"  : "The first step towards integrating any of the 25+ features included in Firebase is creating a new Firebase project. The same project can be used across for multiple apps, but only one per platform. For example, a web app, Android app, and iOS app can all use the same project. This post is part of the Firebase tutorial series.\n",
      "url"      : "/creating-a-new-firebase-project/",
      "date"     : "Sep 23, 2018",
      "content"  : "The first step towards integrating any of the 25+ features included in Firebase is creating a new Firebase project. The same project can be used across for multiple apps, but only one per platform. For example, a web app, Android app, and iOS app can all use the same project. This post is part of the Firebase tutorial series.\n\nFirebase console\n\nVisiting the Firebase console page displays an overview of all existing projects, a link to a demo project (requires log-in), as well as a large button to create a new project.\n\nCreate project form\n\nClicking the new project button displays the following screen:\n\n\n\n  Project name: This can be anything you want, and will never be seen by the user. There’s no need to include the platform in this name, as the same project can be used across Android, iOS, and web.\n  Project ID: This is a globally unique identifier for this project, so many common identifiers will already be taken. Firebase will automatically suggest a reasonable name for you, but you can override this if desired. Again, it will never be seen by the user. This cannot be changed later.\n  Analytics location: This defaults to US, but should be changed to your actual country as it affects the currency revenues are displayed in.\n  Cloud Firestore location: This (unsurprisingly) sets where Cloud Firestore stores data. Note that there are only 3 regions available as of this article’s publication, 2 of which are in the US. The only non-US location (west europe) doesn’t support some features (e.g. Cloud Functions).\n  Default settings: This setting toggles sharing Analytics data with Google. This is recommended, as it improves the service in general, and also allows Google’s technical support to diagnose any potential issues.\n  Controller-controller terms: This setting is only available when Default settings are enabled, and confirms that data should be shared according to the Data Protection Terms.\n\n\nSubmitting form\n\nOnce “Create project” is clicked, it may take up to 30 seconds to actually create your project, during which you will see the screen on the left, followed eventually by the screen on the right:\n\n\nWhen “Continue” is clicked, project setup is complete! You’ll then be taken to the Firebase dashboard, and prompted to integrate Firebase into your app. This topic will be covered in the next post. For help with implementing a specific Firebase feature, please view the other Firebase posts.\n\nNext: Adding Firebase to an Android Project\n"
    } ,
  
    {
      "tags"     : "Drawable, Kotlin, LayerList, UI, Vector",
      "title"    : "Recolouring / modifying multi-layer drawables dynamically in Android",
      "excerpt"  : "Often when creating interfaces in Android, it can be more efficient to have a single .xml drawable and recolouring it according to requirements, instead of trying to include all possible colours in advance. Similarly, it can be more efficient to replace the drawable used inside another drawable dynamically. However, if this needs to be done multiple times within one drawable it becomes a bit more complex, as any modifications will affect the entire drawable.\n",
      "url"      : "/recolouring-modifying-multi-layer-drawables-dynamically-in-android/",
      "date"     : "Sep 14, 2018",
      "content"  : "Often when creating interfaces in Android, it can be more efficient to have a single .xml drawable and recolouring it according to requirements, instead of trying to include all possible colours in advance. Similarly, it can be more efficient to replace the drawable used inside another drawable dynamically. However, if this needs to be done multiple times within one drawable it becomes a bit more complex, as any modifications will affect the entire drawable.\n\nThis post is also available as a Gist.\n\nCreating the drawable XML\n\nFor this example, a simple drawable with a coloured circle background (ID background_circle) and a vector image (ID foreground_icon) will be used. The following .xml should be placed at /res/drawable/dynamic_drawable.xml:\n\n&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;layer-list xmlns:android=\"http://schemas.android.com/apk/res/android\"&gt;\n    &lt;item\n        android:id=\"@+id/background_circle\"&gt;\n        &lt;shape android:shape=\"oval\"&gt;\n            &lt;solid android:color=\"@color/orange\" /&gt;\n        &lt;/shape&gt;\n    &lt;/item&gt;\n    &lt;item android:id=\"@+id/foreground_icon\"&gt;\n        &lt;shape&gt;\n            &lt;solid android:color=\"@android:color/transparent\" /&gt;\n        &lt;/shape&gt;\n    &lt;/item&gt;\n&lt;/layer-list&gt;\n\n\nRecolouring part of the drawable\n\nThe first half of the changes to be made are changing the background colour of our drawable.\n\nFirst, get a reference to your target ImageView (either in a layout or inflated dynamically), and retrieve its drawable as a LayerDrawable (as we need to handle layers):\n\nval layerDrawable = findViewById(R.id.my_drawable).drawable as LayerDrawable\n\n\nNext, get the background layer specifically using the background_circle ID from earlier:\n\nval backgroundDrawable = layerDrawable.findDrawableByLayerId(R.id.background_circle) as GradientDrawable\n\n\nThe colour can now be set using the normal setColor() method:\n\nbackgroundDrawable.setColor(ContextCompat.getColor(context, R.color.my_colour))\n\n\nChanging part of the drawable\n\nThe second half of the changes is changing the foreground drawable.\n\nUsing the layerDrawable from earlier, set the foreground_icon to an existing drawable resource:\n\nlayerDrawable.setDrawableByLayerId(R.id.foreground_icon, ContextCompat.getDrawable(context, R.drawable.new_foreground_icon))\n\n\nThat’s it! Both the composite drawable and background color have been changed, and this technique can be used for as many layers as required.\n\nConclusion\n\nThe ability to create complex dynamic drawables using layer-lists is extremely beneficial when attempting to minimise app size, as it means large areas of an app can use the same base layout, and just customise the small parts that are different.\n\nFor example, in the real world example this post is based on, a total of 5 foreground icons and 7 background colours were possible, meaning a total of 35 different icons were required. Using drawable layer modification, this could all be done within a few lines of code, instead of tens of resources! Much more advanced layer modifications are also possible, to create more complex differences.\n\nAll code used in this post is available as a Gist.\n"
    } ,
  
    {
      "tags"     : "Fonts, Styles",
      "title"    : "Using multi-weighted custom fonts on Android",
      "excerpt"  : "Many apps can use the default Android font, Roboto. However, often clients will have a branded font that must be used that is not included in Android. Luckily, XML fonts (API 16+) solve this issue very neatly. However, these fonts can only be bold, or not bold, yet many fonts have semibold / semilight variants that need to be supported.\n",
      "url"      : "/using-multi-weighted-custom-fonts-on-android/",
      "date"     : "Sep 10, 2018",
      "content"  : "Many apps can use the default Android font, Roboto. However, often clients will have a branded font that must be used that is not included in Android. Luckily, XML fonts (API 16+) solve this issue very neatly. However, these fonts can only be bold, or not bold, yet many fonts have semibold / semilight variants that need to be supported.\n\nPrerequisites\n\nFor this example, the following 4 weights (and 4 italic versions) of The Sans C4s will be used, but of course any custom font can be used:\n\n\n  Semilight (+italic)\n  Regular (+italic)\n  Semibold (+italic)\n  Bold (+italic)\n\n\n.otf versions of each variant were placed in app/src/main/res/font, the same place the XML descriptors will be placed.\n\nFont XMLs\n\nThe core idea is to have two XML fonts defined; one for “semi” weights (semilight and semibold), and one for “regular” weights (regular and bold).\n\nThe first file, the_sans_c4s.xml is for “regular” weights:\n\n&lt;font-family\n    xmlns:app=\"http://schemas.android.com/apk/res-auto\"&gt;\n    &lt;font\n        app:fontStyle=\"normal\"\n        app:fontWeight=\"400\"\n        app:font=\"@font/the_sans_c4s_regular\"/&gt;\n\n    &lt;font\n        app:fontStyle=\"italic\"\n        app:fontWeight=\"400\"\n        app:font=\"@font/the_sans_c4s_regular_italic\"/&gt;\n\n    &lt;font\n        app:fontStyle=\"normal\"\n        app:fontWeight=\"700\"\n        app:font=\"@font/the_sans_c4s_bold\"/&gt;\n\n    &lt;font\n        app:fontStyle=\"italic\"\n        app:fontWeight=\"700\"\n        app:font=\"@font/the_sans_c4s_bold_italic\"/&gt;\n&lt;/font-family&gt;\n\n\nThe second, the_sans_c4s_semi.xml is for “semi” weights:\n\n&lt;font-family\n    xmlns:app=\"http://schemas.android.com/apk/res-auto\"&gt;\n    &lt;font\n        app:fontStyle=\"normal\"\n        app:fontWeight=\"400\"\n        app:font=\"@font/the_sans_c4s_semilight\"/&gt;\n\n    &lt;font\n        app:fontStyle=\"italic\"\n        app:fontWeight=\"400\"\n        app:font=\"@font/the_sans_c4s_semilight_italic\"/&gt;\n\n    &lt;font\n        app:fontStyle=\"normal\"\n        app:fontWeight=\"700\"\n        app:font=\"@font/the_sans_c4s_semibold\"/&gt;\n\n    &lt;font\n        app:fontStyle=\"italic\"\n        app:fontWeight=\"700\"\n        app:font=\"@font/the_sans_c4s_semibold_italic\"/&gt;\n&lt;/font-family&gt;\n\n\nStyles\n\nNow that the basic fonts are ready to use (via android:fontFamily), a very convenient addition is a style for each variant. This allows easily setting a font variant on any element using style=\"Font_SemiBold_Italic\", instead of remembering the right combination of textStyle and fontFamily.\n\nThe full styleset is included below:\n\n&lt;style name=\"Font_Regular\" tools:keep=\"@style/Font_Regular\"&gt;\n&lt;item name=\"android:fontFamily\"&gt;@font/the_sans_c4s&lt;/item&gt;\n&lt;/style&gt;\n\n&lt;style name=\"Font_Regular_Italic\" parent=\"Font_Regular\" tools:keep=\"@style/Font_Regular_Italic\"&gt;\n&lt;item name=\"android:textStyle\"&gt;italic&lt;/item&gt;\n&lt;/style&gt;\n\n&lt;style name=\"Font_Bold\" parent=\"Font_Regular\" tools:keep=\"@style/Font_Bold\"&gt;\n&lt;item name=\"android:textStyle\"&gt;bold&lt;/item&gt;\n&lt;/style&gt;\n\n&lt;style name=\"Font_Bold_Italic\" parent=\"Font_Regular\" tools:keep=\"@style/Font_Bold_Italic\"&gt;\n&lt;item name=\"android:textStyle\"&gt;bold|italic&lt;/item&gt;\n&lt;/style&gt;\n\n&lt;style name=\"Font_SemiLight\"&gt;\n&lt;item name=\"android:fontFamily\"&gt;@font/the_sans_c4s_semi&lt;/item&gt;\n&lt;/style&gt;\n\n&lt;style name=\"Font_SemiLight_Italic\" parent=\"Font_SemiLight\" tools:keep=\"@style/Font_SemiLight_Italic\"&gt;\n&lt;item name=\"android:textStyle\"&gt;italic&lt;/item&gt;\n&lt;/style&gt;\n\n&lt;style name=\"Font_SemiBold\" parent=\"Font_SemiLight\" tools:keep=\"@style/Font_SemiBold\"&gt;\n&lt;item name=\"android:textStyle\"&gt;bold&lt;/item&gt;\n&lt;/style&gt;\n\n&lt;style name=\"Font_SemiBold_Italic\" parent=\"Font_SemiLight\"&gt;\n&lt;item name=\"android:textStyle\"&gt;bold|italic&lt;/item&gt;\n&lt;/style&gt;\n\n\nAdditionally, as these are just simple styles, any existing styles can just set them as a parent to easily customise the font used.\n\nConclusion\n\nWhilst the vast majority of this article is about implementing the existing fonts functionality, extending this to support multiple weights can initially be daunting, since Android only supports bold and/or italic. Hopefully this brief write-up helps others with similar issues.\n\nA Gist of this post is also available.\n"
    } ,
  
    {
      "tags"     : "Kotlin, UI, ViewPager",
      "title"    : "Dynamically preventing scrolling on selected ViewPager pages",
      "excerpt"  : "ViewPagers are an extremely powerful UI tool that by default can be swiped left and right freely. In some cases however, it can be useful to prevent the user swiping in certain directions on certain pages, i.e. a “LockableViewPager”. For example, the first 2 pages might have to be passed programmatically, and then all other pages can be navigated between freely.\n",
      "url"      : "/dynamically-preventing-scrolling-on-selected-viewpager-pages/",
      "date"     : "Sep 6, 2018",
      "content"  : "ViewPagers are an extremely powerful UI tool that by default can be swiped left and right freely. In some cases however, it can be useful to prevent the user swiping in certain directions on certain pages, i.e. a “LockableViewPager”. For example, the first 2 pages might have to be passed programmatically, and then all other pages can be navigated between freely.\n\nThis article will implement determining and changing at any time the current permitted swipe direction(s) (left, right, both, neither) using a custom ViewPager, concluding with a full use case. The end result of this article is also available as a Gist.\n\nIncluding custom element\n\nJust replacing ViewPager with the full path of your LockableViewPager is the only change needed in your layout XML.\n\n&lt;com.example.LockableViewPager\n        android:id=\"@+id/pager\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"match_parent\" /&gt;\n\n\nLockableViewPager\n\nFirst, a new class extending ViewPager has to be created, as well as values for the initialXValue (used to determine swipe direction) and direction (used to store permitted swipe direction):\n\nclass LockableViewPager(context: Context, attrs: AttributeSet) : ViewPager(context, attrs) {\n\n    private var initialXValue: Float = 0f\n    private var direction: SwipeDirection? = null\n\n\nAdditionally, an enum of the possible scroll directions needs to be defined outside the class:\n\nenum class SwipeDirection { BOTH, LEFT, RIGHT, NONE }\n\n\nNext, wrappers around the existing onTouchEvent and onInterceptTouchEvent functions have to be added, so any attempts to move between pages can be checked before being acted on:\n\n    override fun onTouchEvent(event: MotionEvent): Boolean {\n        return if (this.isSwipeAllowed(event)) {\n            super.onTouchEvent(event)\n        } else false\n    }\n\n    override fun onInterceptTouchEvent(event: MotionEvent): Boolean {\n        return if (this.isSwipeAllowed(event)) {\n            super.onInterceptTouchEvent(event)\n        } else false\n    }\n\n\nNow, the isSwipeAllowed function from the previous wrappers has to be implemented, returning a boolean. If the permitted direction is BOTH, true can be returned instantly, and the same for NONE and returning false.\n\nWhen the MotionEvent.ACTION_DOWN is fired, the initialXValue is updated, so we know where the swipe started. When any subsequent MotionEvent.ACTION_MOVE event occurs, the initialXValue and swipe event’s x can be used to calculate which way the user is swiping. The function can then return whether or not the swipe event is in a permitted direction.\n\n    private fun isSwipeAllowed(event: MotionEvent): Boolean {\n        if (this.direction === SwipeDirection.BOTH) {\n            return true\n        } else if (direction === SwipeDirection.NONE) {\n            return false\n        }\n\n        if (event.action == MotionEvent.ACTION_DOWN) {\n            initialXValue = event.x\n            return true\n        }\n\n        if (event.action == MotionEvent.ACTION_MOVE) {\n            try {\n                val diffX = event.x - initialXValue\n                if (diffX &gt; 0 &amp;&amp; direction === SwipeDirection.RIGHT) {\n                    // swipe from left to right detected\n                    return false\n                } else if (diffX &lt; 0 &amp;&amp; direction === SwipeDirection.LEFT) {\n                    // swipe from right to left detected\n                    return false\n                }\n            } catch (e: Exception) {\n                e.printStackTrace()\n            }\n        }\n        return true\n    }\n\n\nFinally, a simple function for setting the permitted swipe direction is added, and then the core of the LockableViewPager is finished.\n\nUsing LockableViewPager\n\nTo use the new LockableViewPager, just set your desired swipe direction during onCreate / onViewCreated:\n\npager.setAllowedSwipeDirection(SwipeDirection.LEFT)\n\n\nExample use case: unskippable pages\n\nThis code was originally used for inviting other users to an account. In this use case, some users were required (e.g. couldn’t be skipped), whereas others were optional (e.g. could be skipped). As such, the required users were displayed first, and had to be passed by completing an invite process which then programmatically moved to the next page. Required users could not be swiped away, but the subsequent optional users could be swiped between freely.\n\nFirst, during the onCreate / onViewCreated, a custom page change listener is set using pager.addOnPageChangeListener(pageChangeListener()) so that swipe logic can be updated whenever a new page is navigated to. This listener is defined as:\n\n    private fun pageChangeListener(): ViewPager.SimpleOnPageChangeListener =\n        object : ViewPager.SimpleOnPageChangeListener() {\n            override fun onPageSelected(position: Int) {\n                setSwipeability()\n            }\n        }\n\n\nsetSwipeability is just a wrapper around pager.setAllowedSwipeDirection(getSwipeDirection(pager)), which calls the main logic getSwipeDirection.\n\nFirst, if the current user is required, no swiping is permitted:\n\n        if (isDriverRequired(pager.currentItem)) {\n            return SwipeDirection.NONE\n        }\n\n\nNext, various useful but simple values are calculated, to ensure there are no unreadably complicated boolean logic statements. The number of pages in the LockableViewPager is used extensively, and each statement builds on the last to avoid repeated logic.\n\n        val isFirstUser = pager.currentItem == 0\n        val isLastUser = pager.currentItem == pager.adapter!!.count - 1\n        val isUserToLeft = !isFirstUser &amp;&amp; pager.currentItem &gt; 0\n        val isUserToRight = !isLastUser &amp;&amp; pager.currentItem &lt; pager.adapter!!.count - 1\n        val isOptionalUserOnLeft = isUserToLeft &amp;&amp; !isUserRequired(pager.currentItem - 1)\n        val isOptionalUserOnRight = isUserToRight &amp;&amp; !isUserRequired(pager.currentItem + 1)\n\n\nNow that all the information required to calculate the permitted swipe directions has been calculated, the actual end logic is extremely simple:\n\n        if (isOptionalUserOnLeft &amp;&amp; isOptionalUserOnRight) {\n            return SwipeDirection.BOTH\n        } else if (isOptionalUserOnLeft) {\n            return SwipeDirection.LEFT\n        } else if (isOptionalUserOnRight) {\n            return SwipeDirection.RIGHT\n        } else {\n            return SwipeDirection.NONE\n        }\n\n\nConclusion\n\nWhilst the initial idea of having varying swipe options on a per-page basis seems simple, the default ViewPager has no capabilities for this. Luckily, the extension described in this post adds the functionality in a very easy to use way, and has no noticeable performance impact.\n\nFurther improvements would be adding an optional “bounce” animation when trying to navigate in a non-permitted direction, instead of just ignoring the swipe. The getSwipeDirection function could also be improved by reducing the amount of if statements and distinct boolean statements, albeit at a risk of decreased readability.\n\nAs mentioned before, all of this code is available as a Gist. Additionally, the core locking idea is originally from andre719mv‘s answer on StackOverflow.\n"
    } ,
  
    {
      "tags"     : "Locale, Localisation, Loco, Resources, Translation",
      "title"    : "Loco 3: Exporting strings",
      "excerpt"  : "Loco is a translation management tool with a staggering array of features, and a very reasonable free plan. This series of guides will cover the basics of using Loco, continuing with Part 3: Exporting strings in a variety of formats.\n",
      "url"      : "/loco-3-exporting-strings/",
      "date"     : "Sep 5, 2018",
      "content"  : "Loco is a translation management tool with a staggering array of features, and a very reasonable free plan. This series of guides will cover the basics of using Loco, continuing with Part 3: Exporting strings in a variety of formats.\n\nThese articles are not sponsored!\n\nTo export strings, a user needs to have the “Access developer tools” permission. The following options and formats are available\n\nOptions (help)\n\n\n\n\n  Locale selection: Locale selection allows you to either export a single, multiple or all locales. If multiple are selected, a zip file will be provided with each file inside a folder structure suited for the export format (4).\n  Locale fallback: Specifying a default locale allows missing strings to be provided with a default translation, this can be useful when a translation has not been completed yet, but all strings are required to build the project.\n  Tag filter: Multiple tags can be used to ensure only the relevant strings are exported. For example, a “Password Reset” module of an app may only need the strings tagged “Password Reset”. More info on tags.\n  File format: The format of the exported data. This will be covered fully in the next section.\n  Index: This specifies what ID should be used for the text. Usually this will be the string name (“Asset ID”), but for some use cases it may be useful to use a different locale’s full string.\n  Order: By default, strings are ordered by date added, this options provides the ability to order by a string’s Asset ID instead.\n  Status: Similar to the Tag Filter, this allows only exporting strings that have a specific status / flag, for example only exporting translated strings.\n  API Endpoint: The URL to call to export strings at the current settings, this will be covered in more detail in Part 4 of this series.\n\n\nFormats\n\nThe full list of basic export formats is reproduced below:\n\n\n  .pot .po .mo: Gettext PO, POT and binary MO\n  .tmx: Translation Memory eXchange\n  .xlf .xliff: Localization Interchange File Format\n  .csv: Comma separated values\n  .sql: MySQL INSERT statements\n  .resx: ResX for .NET framework\n  .html: HTML table\n  .strings: iOS Localizable strings\n  .stringsdict: iOS plural rules\n  .plist .bplist: Apple property list XML and binary formats\n  .properties: Java properties file\n  .ts: An XML format for Qt Framework\n\n\nAdditionally, the following formats have multiple options available:\n\n\n  .json: Available in Chrome, Jed, or i18next language pack formats.\n  .php: Available in a variety of framework formats, specifically Zend, Symfony (array or INI), Code Igniter, or as constant definitions.\n  .xml: Available in Java properties or Tizen format.\n  .yml: Available in Simple YAML, Symfony YAML, Ruby on Rails YAML, or a generic nested format.\n\n\nNotes\n\nIn many agile projects, string management may be ongoing through the product’s development, particularly if multiple locales are being used. Exporting a full set of Loco data before each new build ensures any updated translations are automatically included, meaning updating all string is just a couple of clicks away instead of manually editing files!\n"
    } ,
  
    {
      "tags"     : "Locale, Localisation, Loco, Resources, Translation",
      "title"    : "Loco 2: Collaborating with others",
      "excerpt"  : "Loco is a translation management tool with a staggering array of features, and a very reasonable free plan. This series of guides will cover the basics of using Loco, continuing with Part 2: Collaborating with others, covering comments, roles, and change history.\n",
      "url"      : "/loco-2-collaborating-with-others/",
      "date"     : "Aug 30, 2018",
      "content"  : "Loco is a translation management tool with a staggering array of features, and a very reasonable free plan. This series of guides will cover the basics of using Loco, continuing with Part 2: Collaborating with others, covering comments, roles, and change history.\n\nThese articles are not sponsored!\n\nViewing team\n\nMost commercial projects will end up with at least a few developers, a project manager or two, and various translators. The project used for this article currently has a total of 18 users in a mixture of countries and roles.\n\nYour team is accessed via the “users” icon in the top right, and will show the roles of all team members, as well as precisely which permissions they have been given.\n\n\nClicking a team member will let you view some basic information such as locale and last login. Additionally, if your account has the “Manage project permissions” permission you can modify that user’s access to Loco, covered further in the next section.\n\nAdding new users\n\nAdding a new user requires the “Add new project members” permission, and is accessed via the “Invite new team member” button. Existing users in other projects can be added, or an email address and name (optional) can be submitted.\n\nAfter these details have been entered, the user’s role must be picked. If on the free plan, only Translator (edit existing strings for one or more languages) can be selected. If on a paid plan, an existing project role can be selected (by default Administrator, Developer, or Project Manager), or custom roles can be created. More info on custom roles is available on the Loco site.\n\n\nOnce the user has been invited, they will receive an invitation email inviting them to create an account and gain access to the project. Note that users will only have a profile picture if they have logged in using a third party login (Facebook, Twitter, GitHub).\n\nComments\n\nAll strings can be commented on, and users can be tagged to ensure they are notified of the comment. This extra opportunity to interact with the other users provides an excellent way for translators to directly request clarification from the developers who originally added a string.\n\n\nString history\n\nFree plans can view previous and current translations, but paid plans have a full history of all changes. The comparison selector will be familiar to any wikipedia editors, and provides information on the user, action, and time of action.\n\n\nSelecting two revisions will compare any differences between the strings, with the option to view the difference horizontally or vertically, and revert an earlier change.\n\n\nNotifications (info)\n\nNotifications are by default received for all languages on all projects, and provide updates on new strings, provisional strings, and completed strings. Additionally, by default Loco will email you regularly with changes, this can be turned off via the notification settings though.\n\n\nSummary\n\nOverall, Loco’s collaboration functionality goes above and beyond similar offerings, and the string history ensures the source of any unexpected text can easily be tracked down. Additionally, clarifying translations and adding additional users is very straightforward. Considering only a single user needs to pay for the paid plans, and unlimited extra users can be added, the plans are likely to be worth it for most companies for the custom roles / full string history alone! A detailed comparison of the plans is available in Part 1.\n"
    } ,
  
    {
      "tags"     : "Locale, Localisation, Loco, Resources, Translation",
      "title"    : "Loco 1: String management for multi-platform & multi-locale projects",
      "excerpt"  : "Loco is a translation management tool with a staggering array of features, and a very reasonable free plan. This series of guides will cover the basics of using Loco, starting with Part 1: Creating a project and adding strings.\n",
      "url"      : "/loco-1-string-management-for-multi-platform-multi-locale-projects/",
      "date"     : "Aug 29, 2018",
      "content"  : "Loco is a translation management tool with a staggering array of features, and a very reasonable free plan. This series of guides will cover the basics of using Loco, starting with Part 1: Creating a project and adding strings.\n\nThese articles are not sponsored!\n\nCreating an account\n\nFirst, create an account with either your email, or using GitHub, Twitter, or Facebook login. Once your email has been confirmed / permission has been given, a super simple signup screen asks for a password and not much more.\n\n\nCreating a project\n\nA default project will be created for you upon signup, with customisable URL, name, and description. The URL for your project will be the very simple https://localise.biz/username/project.\n\nAdding locales\n\nNext, add the locales / languages the strings should be translated into via the + button next to your default locale in the top left of the “Manage” tab. Locales can be anything from a simple language (e.g. French) into a fully custom identifier. A particularly useful feature is the ability to rename locales, which can be extremely useful when the same text needs to be translated into the same language multiple times (e.g. different brands within the same country).\n\n\nAdding strings\n\nIt’s finally time to start actually adding text to translate, or “Assets”. Click “New asset” and a popup will appear which can be a little overwhelming!\n\n\n  Source text is the initial text to use, in the project’s native locale (e.g. English).\n  Asset ID is the name used to reference the text in code. This will be something like Dialog_Title_IncorrectPassword or dialog-title-incorrectpassword depending on your preferred style.\n  Context is used when a text’s use is ambiguous, but is generally not needed for most use cases due to Notes.\n  Type should almost always be “Plain text”, unless HTML is needed.\n  Tags are a powerful way of categorising strings, as each string can have one or more. A common use case is adding a tag per screen (e.g. “Login”, “Registration”), so that all the strings for a specific screen can easily be viewed at once. Shared strings will have multiple screen tags.\n  Notes are a way to provide extra information to translators, generally used if the Asset ID and Tags by themselves are not descriptive enough.\n\n\n\n\nString statuses\n\nOnce a string has been added, it will by default have the status of “Translated” in the original locale, and “Untranslated” in all other locales. These statuses can be changed at will, and feature 5 different “in progress” states to help collaboration between different project teams. For example, in a recent project new strings were marked as “Provisional” when they had been translated by developers, “Unapproved” when a professional translator had corrected mistakes, and “Translated” when a line manager had signed off a translation.\n\n\nPlan pricing\n\nLoco’s free plan is usually generous enough for almost all use cases, even for large projects with a few hundred assets, multiple languages, and many translators. At my company we went for the “Pro” plan, as we needed custom roles for certain individuals. This cost us a grand total of just £4.95/month (approximately $6.50)!\n\nMore information on these quotas are available on Loco’s help pages, and a brief explanation is below. It’s worth emphasising that only the project owner needs to pay, and all other project collaborators can benefit.\n\n\n  Translations refers to the total number of translations used across the entire account. The default limit of 2,000 is equal to a project with 500 strings translated into 3 languages (plus original language). A relatively large app will likely have between 300-600 assets, keeping in mind common text (e.g. “OK”) can share the same asset.\n  Collaboration refers to the roles that invited users can have. This will be covered in-depth in a later post, but essentially the free plan allows unlimited translators (can only edit translations), but no additional roles.\n  Projects unsurprisingly refers to the number of projects that can be added to an account.\n  Translatable assets refers to the number of assets that can be included in a single project. The free plan’s limits of 2 projects and 1,000 assets per project give the total of 2,000 available translations.\n  Languages refers to the number of different locales / languages that can be added to a project.\n  Revision history refers to the ability to see an asset’s history (e.g. who changed status, text, etc). Whilst the free plan’s “see previous version” is useful, being able to view a full history is essential for larger projects.\n  Extra translations refers to the ability to purchase more translations if the very generous limits are reached.\n\n\nAdditional features\n\nIndividual strings can also have plurals and placeholders (e.g. %1$s for Android) configured, all changes logged, and comments with user tagging support.\n\nIn addition to Loco’s core features, a few free utilities are provided such as iOS Android string conversion, or conversion between all common formats.\n\nLoco has such a massive set of features that only the very basics have been covered here. Collaboration, exporting, and command line interface will all be covered in later articles.\n"
    } ,
  
    {
      "tags"     : "Backups, Generics, SharedPreferences, Utility, Java",
      "title"    : "Generic SharedPreferences Utility Class",
      "excerpt"  : "Recently, a project required both backed up and non-backed up SharedPreferences, as well as an easy way to read and write these values. The following class was created with this functionality, using generics in Kotlin for practice. This post will walkthrough some of the key features, the finished code is also available as a Gist.\n",
      "url"      : "/generic-sharedpreferences-utility-class/",
      "date"     : "Aug 28, 2018",
      "content"  : "Recently, a project required both backed up and non-backed up SharedPreferences, as well as an easy way to read and write these values. The following class was created with this functionality, using generics in Kotlin for practice. This post will walkthrough some of the key features, the finished code is also available as a Gist.\n\nGeneric get &amp; set\n\nMost importantly, the datatype to read / write is determined by the default value passed. E.g. if the default datatype is a string, getString will be used. This can be a problem when storing numbers, as passing a long for a value saved as an int will not return the correct SharedPreference.\n\nThe result of the SharedPreference setting is returned as a boolean so the caller can have confidence in the save’s success.\n\nfun set(key: String, value: T, toBackedUp: Boolean = true): Boolean {\n    val preferences = if (toBackedUp) backedUpPreferences else nonBackedUpPreferences\n    if (preferences != null &amp;&amp; !TextUtils.isEmpty(key)) {\n        val editor = preferences.edit()\n        when (value) {\n            is String -&gt; editor.putString(key, value)\n            is Long -&gt; editor.putLong(key, value)\n            is Int -&gt; editor.putInt(key, value)\n            is Float -&gt; editor.putFloat(key, value)\n            is Boolean -&gt; editor.putBoolean(key, value)\n            else -&gt; return false\n        }\n        return editor.commit()\n    }\n    return false\n}\n\n\nBacked up and non-backed up preferences\n\nAs some preferences should be backed up (e.g. user choices), and others not (e.g. current app state), there are 2 SharedPreferences files used. By default, all values are read from / written to the backed up file, but this can be overridden by passing false to the get / set function.\n\nprivate val backedUpPreferences: SharedPreferences?\nprivate val nonBackedUpPreferences: SharedPreferences?\n\ninit {\n    backedUpPreferences = application.getSharedPreferences(BACKED_UP_NAME, MODE_PRIVATE)\n    nonBackedUpPreferences = application.getSharedPreferences(NON_BACKED_UP_NAME, MODE_PRIVATE)\n}\n\ncompanion object {\n    private const val BACKED_UP_NAME = \"com.yourcompany.BACKED_UP\"\n    private const val NON_BACKED_UP_NAME = \"com.yourcompany.NON_BACKED_UP\"\n}\n\n\nThe backup logic is added via a file called backup_rules.xml, in /src/main/res/xml containing the following:\n\n&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;full-backup-content&gt;\n    &lt;include domain=\"sharedpref\" path=\"com.yourcompany.BACKED_UP.xml\" /&gt;\n&lt;/full-backup-content&gt;\n\n\nThe following should also be added to the AndroidManifest.xml inside the application element:\n\n        android:allowBackup=\"true\"\n        android:fullBackupContent=\"@xml/backup_rules\"\n\n\nLegacy support\n\nTo ensure that legacy (non-generic) SharedPreferences uses can be easily replaced, get &amp; set wrappers are provided for the 4 major types (string, long, integer, boolean).\n\n    fun getStringPreference(key: String, defaultValue: String = \"\"): String = get(key, defaultValue)\n    fun getLongPreference(key: String, defaultValue: Long = 0L): Long = get(key, defaultValue)\n    fun getIntegerPreference(key: String, defaultValue: Int = 0): Int = get(key, defaultValue)\n    fun getBooleanPreference(key: String, defaultValue: Boolean = false): Boolean = get(key, defaultValue)\n\n    fun setStringPreference(key: String, value: String): Boolean = set(key, value)\n    fun setLongPreference(key: String, value: Long): Boolean = set(key, value)\n    fun setIntegerPreference(key: String, value: Int): Boolean = set(key, value)\n    fun setBooleanPreference(key: String, value: Boolean): Boolean = set(key, value)\n\n\nPossible improvements\n\nCurrently, any object can be passed to the getters or setters, not just the 4 supported types. A future improvement would be to only accept values actually supported for storage.\n\nAdditionally, a way to enforce certain keys always getting / setting the same type would help prevent hard to track down errors, as would checking both SharedPreferences files for a given key.\n\nAll code is available in a Gist.\n"
    } ,
  
    {
      "tags"     : "ActionBar, Layout, Styles",
      "title"    : "Creating a custom Android ActionBar",
      "excerpt"  : "By default, new Android projects have an ActionBar at the top (also known as a title bar), which usually contains a title, an optional back button on the left, and optional action(s) on the right. For many cases, minor customisations to colour are enough, but if a project requires exactly meeting a client’s design more advanced functionality will need to be utilised.\n",
      "url"      : "/creating-a-custom-android-actionbar/",
      "date"     : "Aug 22, 2018",
      "content"  : "By default, new Android projects have an ActionBar at the top (also known as a title bar), which usually contains a title, an optional back button on the left, and optional action(s) on the right. For many cases, minor customisations to colour are enough, but if a project requires exactly meeting a client’s design more advanced functionality will need to be utilised.\n\nThis tutorial will walk through the steps needed to turn a default ActionBar into a fully customised area of the screen, whilst keeping useful functionality like displaying a back button intact. Kotlin is used for this sample project, but all code can be easily converted to Java.\n\nRetrieving the ActionBar\n\nRetrieving the ActionBar is a simple case of myBar = actionBar!! in an Activity, or myBar = supportActionBar!! in an AppCompatActivity. The assignment is forced (!!) since we know the action bar will exist.\n\nRemoving default effects\n\nFirst, the elevation needs to be removed using myBar.elevation = 0f. By default, the elevation causes shadow to be cast on the rest of your screen, and also forces a potentially unwanted dividing line between the ActionBar. Once this is removed, the action bar can blend seamlessly into the content of the app (once we set up a custom view later on).\n\n\n\nCreating a custom layout\n\nNow our custom layout needs to be created. The design of this of course depends on your requirements, but the overall structure should be a RelativeLayout at res/layout/element_toolbar.xml with the following layout parameters:\n\n&lt;RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\nandroid:layout_width=\"match_parent\"\nandroid:layout_height=\"wrap_content\"\nandroid:layout_gravity=\"fill_horizontal\"&gt;\n\n\nThis layout functions just like any other layout file, and can be filled with ImageViews, TextViews, etc.\n\nSetting a custom layout\n\nNext, our custom layout needs to be enabled and configured:\n\nmyBar.setDisplayShowCustomEnabled(true)\nmyBar.setCustomView(R.layout.element_toolbar)\n\n\nAdditionally, since we’re going to be handling title text in our element_toolbar.xml, we should turn off displaying text:\n\nmyBar.setDisplayShowTitleEnabled(false)\n\n\n\n\nWe now have a custom toolbar! However, there’s a pretty glaring issue, in that our custom layout doesn’t actually reach the edges of the ActionBar, so the default design can still be seen. To fix that we need to…\n\nOverride ActionBar background\n\nFirst, inside AppTheme in /res/values/styles.xml add the following line:\n\n&lt;item name=\"actionBarStyle\"&gt;@style/CustomBar&lt;/item&gt;\n\n\nAnd add the following style inside the same file, but outside of AppTheme:\n\n&lt;style name=\"CustomBar\" parent=\"Widget.AppCompat.ActionBar.Solid\"&gt;\n    &lt;item name=\"background\"&gt;@android:color/black&lt;/item&gt;\n&lt;/style&gt;\n\n\n\n\nNext steps\n\nAn example project is provided for this tutorial, with an example of how to set click events for items inside your custom ActionBar. It can be downloaded / forked from GitHub.\n\nIf you have any questions about the topic covered, please comment or join the Android Dev discord.\n"
    } ,
  
    {
      "tags"     : "Google Play Services, Gradle, Modules, OneSignal",
      "title"    : "Getting OneSignal Working On A Multi-Module Project",
      "excerpt"  : "Recently, upon attempting to implement OneSignal for user notifications (and following their installation instructions), a wide variety of intriguing and mysterious build errors were encountered.\n",
      "url"      : "/getting-onesignal-working-on-a-multi-module-project/",
      "date"     : "Aug 19, 2018",
      "content"  : "Recently, upon attempting to implement OneSignal for user notifications (and following their installation instructions), a wide variety of intriguing and mysterious build errors were encountered.\n\nThe root cause of these seemed to be their gradle plugin (ironically intended to simplify the dependency process, and solve any Google Play Services issues) causing issues when attempting to be applied to a project with 10+ modules inside it. Luckily, the fix was pretty straight forward.\n\nFirst, a few of the errors encountered:\n\n\n  com.google.android.gms:play-services-measurement-base is being requested by various other libraries\n  Android dependency is set to compileOnly/provided which is not supported\n  Error: Program type already present: com.google.android.gms.internal.measurement.zzwo\n  java.lang.NoClassDefFoundError: com.google.android.gms.gcm.GoogleCloudMessaging\n  Duplicate key com.android.build.gradle.internal.api.artifact.BuildableArtifactImpl@7c139f68\n\n\nThe reason behind these issues ultimately boiled down to:\n\n\n  The Gradle plugin being useful in an ideal situation, but just muddying the waters if trying to resolve an issue manually.\n  The library’s build.gradle containing a few old Google Play Services dependencies (e.g. 12.0.1), and some unusual syntax.\n  The OneSignal library not being designed for a project with many modules.\n\n\nThe solution settled on was unfortunately not at all ideal, but it did get notifications working perfectly:\n\n\n  Remove all code to do with the Gradle plugin, it’s not necessary.\n  Download the module as a .zip and import it into your project manually.\n  Update the Google Play Services version to the same as the rest of your project.\n  Add implementation ‘com.google.android.gms:play-services-ads:15.0.1' to the new submodule’s build.gradle, or a few files within won’t compile.\n  Fix a couple of files that have missing imports.\n  Resync Gradle, and skip to Step 2 of the OneSignal setup docs.\n  Note: If you’re using build flavours, make sure you change those in the new submodule to match your own.\n\n\nWhilst the solution did work, unfortunately it’s a very hacky approach, just downloading the library and manually messing the the gradle files. Hopefully in the future the OneSignal library’s multi module support improves.\n"
    } ,
  
    {
      "tags"     : "Database, Java, ORM, SugarORM, Tutorial",
      "title"    : "Getting Started with Sugar ORM",
      "excerpt"  : "Sugar is a very easy to use ORM library used to make handling databases on Android hassle-free. Whilst it lacks some features, it is ideally suited to smaller projects due to the simple syntax.\n",
      "url"      : "/getting-started-with-sugar-orm/",
      "date"     : "Jul 7, 2017",
      "content"  : "Sugar is a very easy to use ORM library used to make handling databases on Android hassle-free. Whilst it lacks some features, it is ideally suited to smaller projects due to the simple syntax.\n\nThere is official documentation, but it misses a few key points, so this article will serve as an alternative “Getting Started” guide. It also highlights a few vital options that aren’t mentioned in the official guide, and is geared towards those new to Android who want an easy way to setup a local database.\n\nSetting Up\n\nSetting up Sugar is very straightforward, and contains just three simple steps.\n\n1. Adding the library\n\nAs with any other Gradle library, add the following to your build.gradle dependencies, and perform a rebuild (Android Studio will prompt to do this automatically). This will let us reference the library’s functionality:\n\ncompile 'com.github.satyan:sugar:1.5'\n\n\n2. Connecting app to Sugar\n\nSo that Sugar can run when the application starts, and perform other tasks, it needs to be created and destroyed when the application is, not an individual activity. To do this, we need to make a new class that extends Application, which we can then use to initialise Sugar and other services. I generally put this file outside of any subfolders in the project structure, but it can go anywhere.\n\npublic class MainApplication extends Application {\n    @Override\n    public void onCreate() {\n        super.onCreate();\n        SugarContext.init(this);\n    }\n\n    @Override\n    public void onTerminate() {\n        super.onTerminate();\n        SugarContext.terminate();\n    }\n}\n\n\nNow that we have our MainApplication class, we need to define it in the AndroidManifest.xml. To do this, just add / modify the android:name= attribute on `` to point to .MainApplication. If you placed the new class in a subfolder, it will be at .Subfolder.MainApplication:\n\n&lt;application\n    android:name=\".MainApplication\"\n\n\n3. Configuring options\n\nFinal step! All that’s left to do is configure a few options. These are all inside the &lt;application tag in AndroidManifest.xml in the format ``:\n\n\n  \n    \n      Name\n      Value\n      Description\n    \n  \n  \n    \n      DATABASE\n      yourapp.db\n      The name of your database file. This can be anything, but it’s generally simpler to just use your app’s name.\n    \n    \n      VERSION\n      1\n      The version of your database. Update this when you add new columns / tables to automatically update your database.\n    \n    \n      QUERY_LOG\n      false\n      Whether every query should be written to the log. This can slow down your app, but can be useful during development.\n    \n    \n      DOMAIN_PACKAGE_NAME\n      com.yourpackagename.model\n      Where your entities are stored. It’s cleanest to use a subfolder that only contains these classes.\n    \n  \n\n\nThat’s it, you’re good to go! The rest of this guide will cover creating your entities / model, and basic usage.\n\nUsing Sugar\n\nCreating entities\n\nIn this example, we’ll use a simple table with just an id and a text.\n\n@Table(name=\"mytable\")\npublic class Text extends SugarRecord {\n    @Column(name = \"a\") private Long id;\n    @Column(name = \"b\") private String text;\n\n    public Text() {}\n\n    public Text(Long id, String text) {\n        this.id = id;\n        this.text = text;\n    }\n\n    @Override\n    public Long getId() {\n        return id;\n    }\n\n    @Override\n    public void setId(Long id) {\n        this.id = id;\n    }\n\n    public String getText() {\n        return text;\n    }\n\n    public void setText(String text) {\n        this.text = text;\n    }\n}\n\n\nThe first thing to look at is the most important, the extends SugarRecord. This lets Sugar know that this is a database table. In this example, we’ve used @Table(name= to tell Sugar to save the table under “mytable” instead.\n\nNext, we declare the columns we want to include, and create getters and setters for them. As before, we can use @Table(name= to set a custom name if desired. Note that id is the built-in Sugar primary key, hence the @Override. It can optionally be included in your schema, or handled invisibly by Sugar.\n\nFinally, we add a constructor with all parameters, and one with none. A constructor taking no parameters is required by Sugar ORM, and the table will not be usable without it. All of the getters / setters / constructors can be created by Android Studio by pressing Alt + Insert inside the class.\n\nSaving data\n\nData can be saved by creating a new instance of the object, and calling .save() on it. This can also be included in your constructor if auto-save is desired.\n\nText text = new Text(1, \"Example text\");\ntext.setText(\"New test\");\ntext.save();\n\n\nLoading data\n\nData can be loaded from the database by id, using the query builder, or directly using SQL. All 3 of the following examples return the same result, the Text object with id 1.\n\n\n  Using primary key id: \n Text.findById(Text.class, 1);\n\n  Using query builder: \n Select.from(Text.class)\n         .where(\n                 Condition.prop(\"a\").eq(1)\n         ).first();\n\n  Using SQL: \n Text.find(Text.class, \"a = 1\").get(0);\n\n\n\nNote that the 2nd and 3rd methods return a List, and we’re selecting the first record. The correct method to use depends on the situation, but looking rows up by their primary key is generally a good idea if possible for performance reasons.\n\nConclusion\n\nI’ve personally used Sugar for a few of my projects, such as Pixel Blacksmith and Blacksmith Slots, and found the simple syntax and speedy performance very helpful. However, colleagues have used it on more complex projects and found it lacking, so it may not be suitable for large scale commercial projects.\n\nIt also doesn’t receive many updates, but as it is relatively bug free due to the simple nature of it, this is less of an issue. Unfortunately it seems support and repository maintenance are lacking, but I still strongly recommend it for smaller projects.\n\nAs a reminder, there is official documentation, and some further reading on the repository which may be helpful to refer to.\n\nAll code used in this article is available as a Gist.\n"
    } ,
  
    {
      "tags"     : "Landscape, Orientation, Portrait, User Options",
      "title"    : "Auto-detecting Device Orientation Whilst Allowing User to Override",
      "excerpt"  : "When creating games (and other apps), screen orientation is very important. In general, more casual games use portrait, whilst more hardcore / intense games use landscape. However, some games may be inbetween these two categories, or may wish to reach a wider audience by supporting both. Automatically rotating to match device orientation is easy, but allowing the user to “lock” one orientation is a little trickier.\n",
      "url"      : "/auto-detecting-device-orientation-whilst-allowing-user-to-override/",
      "date"     : "Jun 13, 2017",
      "content"  : "When creating games (and other apps), screen orientation is very important. In general, more casual games use portrait, whilst more hardcore / intense games use landscape. However, some games may be inbetween these two categories, or may wish to reach a wider audience by supporting both. Automatically rotating to match device orientation is easy, but allowing the user to “lock” one orientation is a little trickier.\n\nThe Solution\n\nFirst, we’re going to store the user’s current preference (auto, landscape, or portrait), then this is going to be applied whenever an activity resumes. It is applied on resume instead of on create, to ensure reusing / reentering activities does not cause the app to switch between orientations.\n\nNow, ensure all the activities you want to be rotatable (almost certainly all) are not specifying orientation under configChanges. If it is specified, it tells the device that the app will handle orientation changes, when we actually want the device to do the hard work for us.\n\nNext, implement the following into a BaseActivity and ensure all activities extend is (recommended), or implement it into each activity. setRequestedOrientation() informs the device which orientation we want to use, then the user’s preference is loaded. The actual implementation of preference saving could just as easily be a shared preference, this implementation uses an ORM object.\n\n@Override\nprotected void onResume() {\n    super.onResume();\n\n    //noinspection ResourceType\n    setRequestedOrientation(Setting.get(Enums.Setting.Orientation).getIntValue());\n}\n\n\nNote that the //noinspection ResourceType is required as we are passing an integer value directly, instead of using a constant. Suppressing errors is generally bad practice, but in this case it’s unavoidable due to the programmatic nature of the orientation.\n\nThe integers to use for orientations are available directly from the Android source (line 395+), but we only care about 3 in particular, which are specified as internal constants for simplicity. They’re self explanatory, with 4 (auto) being the default.\n\npublic final static int ORIENTATION_AUTO = 4;\npublic final static int ORIENTATION_LANDSCAPE = 6;\npublic final static int ORIENTATION_PORTRAIT = 7;\n\n\nAdding a dropdown or other selector to actually allow the user to pick whether they want auto / landscape / portrait is outside the scope of this article. However, very similar code was used in the “Selecting a Language” section of the previous “Implementing A Locale / Language Selector” article.\n\nAs a starting point, the code used to return the constant to save from the position picked on a dropdown consisting of Auto, Portrait, and Landscape, is as follows:\n\nprivate int getOrientationValue(int position) {\n    switch (position) {\n        case 1: return Constants.ORIENTATION_LANDSCAPE;\n        case 2: return Constants.ORIENTATION_PORTRAIT;\n        default: return Constants.ORIENTATION_AUTO;\n    }\n}\n\n\nThe Conclusion\n\nWhilst the actual code used in this article is very minimal, the overall effect is very user-friendly and powerful. An optional extension to this work would be adding orientation locks for all 4 possible screen orientations, but in this use case just landscape or portrait was sufficient. Note that the constant values still obey the device sensor, meaning if the device is turned upside down whilst landscape locked, it will flip 180° so that it is correctly orientated.\n\nThe majority of apps will likely be able to settle on just one target orientation depending on their audience, but for apps that require targeting both, adding a user override is extremely important. For games in particular, the user may want to play the game in portrait whilst lying on their side, something that would be impossible without an orientation lock as the game would rotate to match gravity.\n\nThe code used in this article is from the upcoming Blacksmith Slots game, and as always the (albeit minimal) code for this article is available as a Gist.\n"
    } ,
  
    {
      "tags"     : "Games, Java, Media Service, Music",
      "title"    : "Selectively Playing Tracks Whilst Game Is Active / Open",
      "excerpt"  : "Playing background music on Android is pretty easy: just start a service with a media player. Great, that was easy! However, when the user presses the home button, the music… continues. This is good for music apps, but awful for games. In this example, Blacksmith Slots had one music track for the intro, and one for the main game.\n",
      "url"      : "/selectively-playing-tracks-whilst-game-is-active-open/",
      "date"     : "Jun 5, 2017",
      "content"  : "Playing background music on Android is pretty easy: just start a service with a media player. Great, that was easy! However, when the user presses the home button, the music… continues. This is good for music apps, but awful for games. In this example, Blacksmith Slots had one music track for the intro, and one for the main game.\n\nThe Solution\n\nThe basic idea for the solution comes from a 5 year old StackOverflow answer, with the only upvote being mine. Essentially, the music is stopped whenever an activity is paused, unless a boolean flag is set. In this implementation, a MusicHelper singleton was used, so that any activity could change audio track if necessary.\n\nMedia Service\n\nThe media service is a relatively basic service that creates a media player and starts it. The code is available on this article’s Gist, but essentially the track to play is passed via a reference to the asset (e.g. R.raw.music) on the service’s start intent.\n\nA reference to the service is stored within the MusicHelper, and assigned by the following:\n\nmusicService = new Intent(context.getApplicationContext(), MusicService.class)\n    .putExtra(\"songId\", trackToPlay);\n\n\nBase Activity\n\nThis article assumes all of the application’s activities extend the same base activity. If this isn’t the case, the following can be implemented on every activity, but this is obviously more effort.\n\nWhen an activity is paused (application exited, user receives a call, starting a new activity, etc) if the movingInApp flag isn’t set, the music is paused.\n\n@Override\npublic void onPause() {\n    super.onPause();\n    if (!MusicHelper.getInstance(this).isMovingInApp()) {\n        MusicHelper.getInstance(this).stopMusic();\n    }\n}\n\n\nWhen an activity resumes the movingInApp flag is set to false, so that the next time an activity pauses it can be checked again.\n\n@Override\nprotected void onResume() {\n    super.onResume();\n    MusicHelper.getInstance(this).setMovingInApp(false);\n}\n\n\nSetting Moving Flag\n\nIn order for the isMovingInApp() check to work, every time an activity is closed or opened, movingInApp must be set to true first. As a base activity was used in this example, a generic close method could be used, but the same code must be called just before starting a new activity too.\n\npublic void close(View v) {\n    MusicHelper.getInstance(this).setMovingInApp(true);\n    finish();\n}\n\n\nPlaying Music\n\nTo play music, the playIfPossible() function can be used, passing the asset that should be played. This will play the track if there is currently no audio playing, or another track is currently being played.\n\nMusicHelper.getInstance(this).playIfPossible(R.raw.village_consort);\n\n\nAs mentioned before, playIfPossible() checks if the track isn’t currently playing, then starts the service if necessary. This is done in a new thread to avoid UI stutters. Note that the project used as an example allows the user to mute music at any time, including before settings have been setup, hence playing if it is intro music, and checking the user’s preference. This is of course optional.\n\npublic void playIfPossible(final int trackToPlay) {\n    new Thread(new Runnable() {\n        public void run() {\n            // If music should be playing, and it isn't, or is the wrong track, fix that!\n            if ((isIntroMusic(R.raw.time_passes) || Setting.getBoolean(Enums.Setting.Music)) &amp;&amp;\n                    (trackToPlay != currentTrack || !musicServiceIsStarted)) {\n                musicService = new Intent(context.getApplicationContext(), MusicService.class)\n                    .putExtra(\"songId\", trackToPlay);\n                currentTrack = trackToPlay;\n                context.startService(musicService);\n                musicServiceIsStarted = true;\n            } else if (!Setting.getBoolean(Enums.Setting.Music) &amp;amp;&amp;amp; musicServiceIsStarted) {\n                context.stopService(musicService);\n                musicServiceIsStarted = false;\n            }\n        }\n    }).start();\n}\n\n\nThe Conclusion\n\nBackground music is absolutely essential in a game, and being able to control this playback is just as important. If a game’s music continues when the app is closed, the user is likely to uninstall it pretty quickly, and understandably so.\n\nThe implementation described in this article will also stop music when the activity is temporarily paused, and start it again when it is resumed. In most cases this isn’t ideal, so the media player’s start and stop functions could probably be replaced with play and pause functions, but it was not necessary for this use case.\n\nI’d also like to say thank you to the user who posted the initial idea, it’s a rather elegant solution to a tricky problem. I’m sure in the 5 years since it was posted, there have been libraries and better solutions discovered, but I was unable to find any. Besides, this one works perfectly!\n\nAs always, all code used in this article is available as a GitHub Gist.\n"
    } ,
  
    {
      "tags"     : "i18n, Language, Locale, Localisation, Java",
      "title"    : "Implementing A Locale / Language Selector",
      "excerpt"  : "Android applications are distributed to users around the world, and these users aren’t always going to speak the same languages as you. Luckily, Android has excellent built-in support for automatically applying the right language, however this isn’t always enough. Sometimes a user may want to choose their language, and unfortunately there’s no built-in way to support this. The game Pixel Blacksmith uses the technique described in this article.\n",
      "url"      : "/implementing-a-locale-language-selector/",
      "date"     : "May 13, 2017",
      "content"  : "Android applications are distributed to users around the world, and these users aren’t always going to speak the same languages as you. Luckily, Android has excellent built-in support for automatically applying the right language, however this isn’t always enough. Sometimes a user may want to choose their language, and unfortunately there’s no built-in way to support this. The game Pixel Blacksmith uses the technique described in this article.\n\nThe Solution\n\nTo allow changing language, the Locale needs to be overridden and set to the user’s choice. How the user selects a language isn’t too important, in this example a spinner was chosen since it was the easiest to work with. This choice is stored as a shared preference that is then applied every time the application launches.\n\nOn Startup\n\nInside the application class, or early on in the main activity, a call to LanguageHelper.updateLanguage() is made, which will handle the locale overwriting. It is passed the application context, which is required to access shared preferences and modify the locale later on.\n\nThis function looks up the saved language from shared preferences, then passes that to the main updateLanguage() function, described in the next section.\n\npublic static void updateLanguage(Context ctx) {\n    String lang = PreferenceManager.getDefaultSharedPreferences(ctx).getString(\"locale\", \"\");\n    updateLanguage(ctx, lang);\n}\n\n\nChanging Locale\n\nWhen a context and 2 character locale (e.g. “en” for English or “es” for Spanish) are passed, this new locale is saved in shared preferences. Then, so long as the language string isn’t empty, a new Locale is created using it, and this Locale is applied using updateConfiguration(). Note that this method now appears to be deprecated, and it doesn’t look like a quick fix, but in your case it may be worth implementing.\n\nprivate static void updateLanguage(Context ctx, String lang) {\n    PreferenceManager.getDefaultSharedPreferences(ctx).edit().putString(\"locale\", lang).apply();\n    Configuration cfg = new Configuration();\n    if (!TextUtils.isEmpty(lang)) {\n        cfg.locale = new Locale(lang);\n    } else {\n        cfg.locale = Locale.getDefault();\n    }\n\n    ctx.getResources().updateConfiguration(cfg, null);\n}\n\n\nSelecting A Language\n\nWhen a language from the spinner is selected, the following onItemSelected() method is called. Most of the code is not specific to this example, but the important line is the LanguageHelper.updateLanguage() method, which is passed a context, and the position selected (+1 to account for zero indexing), which refers to a predefined language ID.\n\npublic void onItemSelected(AdapterView parentView, View selectedItemView, int position, long id) {\n    setting.setIntValue(position + 1);\n    setting.save();\n\n    LanguageHelper.updateLanguage(activity, position + 1);\n    ToastHelper.showPositiveToast(parentView, ToastHelper.SHORT, parentView.getSelectedItem().toString(), true);\n    onResume();\n}\n\n\nThis updateLanguage() wrapper needs to look up the locale string from the ID / position passed. The numbers are sequential for ease of us in this example.\n\npublic static void updateLanguage(Context context, int language) {\n    updateLanguage(context, getLocaleById(language));\n}\n\nprivate static String getLocaleById(int id) {\n    switch (id) {\n        case Constants.LANG_ENGLISH:\n            return \"en\";\n        case Constants.LANG_FRENCH:\n            return \"fr\";\n        ... more languages omitted ...\n        case Constants.LANG_GERMAN:\n            return \"de\";\n    }\n    return \"\";\n}\n\n\nOnce a language string is obtained, the normal updateLanguage() function can be used, and the language is set immediately, and will be automatically reapplied when the application restarts.\n\nThe Conclusion\n\nLocalising applications is essential if users who don’t speak your language are to be engaged. Giving the users the ability to choose their own language gives them an extra element of control, which many will appreciate. It also helps when testing translations during development, as languages can be easily switched, without requiring changing the system Locale, or starting a new emulator.\n\nAll code used in this article is available as a Gist.\n\nSome of the code is modified from a StackOverflow answer.\n"
    } ,
  
    {
      "tags"     : "AlertDialog, Dynamic Dialog, Runnable, Java",
      "title"    : "Custom Alert Dialog With Dynamic Buttons in Android",
      "excerpt"  : "Alert Dialogs are an excellent way of providing a confirmation screen, or letting users select from a set of options. However, customising them can be tricky, and they have a maximum of 3 buttons (positive, neutral, negative), all of which are positioned differently in different Android versions. If advanced customisation or more than 3 buttons are required, the usual method of modifying colours etc (styles) isn’t enough!\n",
      "url"      : "/custom-alert-dialog-with-dynamic-buttons/",
      "date"     : "Apr 29, 2017",
      "content"  : "Alert Dialogs are an excellent way of providing a confirmation screen, or letting users select from a set of options. However, customising them can be tricky, and they have a maximum of 3 buttons (positive, neutral, negative), all of which are positioned differently in different Android versions. If advanced customisation or more than 3 buttons are required, the usual method of modifying colours etc (styles) isn’t enough!\n\nThe Solution\n\nThe core part of the solution is using our own layout for the alert dialog, and handling button creation ourselves. Once we’ve created custom layouts, they’ll need to be populated, and passed Runnables of the actions to be performed.\n\nLayouts\n\nFirst, a layout is required for the dialog, and for the buttons. Examples are available on this article’s gist, but essentially the dialog layout is a simple linearlayout with textviews, and the button layout is just a styled textview.\n\nInflating\n\nThe parameters required to create an AlertDialog using the custom class are context (for inflating), title text, body text, and any number of DialogActions.\n\nA DialogAction is a container object that holds the text to be displayed on a button, and the Runnable that should be run when it is clicked. It doesn’t need any functionality besides getters and setters, so is a very simple construct:\n\npublic class DialogAction {\n    private String text;\n    private Runnable runnable;\n\n    public DialogAction(String text, Runnable runnable) {\n        this.text = text;\n        this.runnable = runnable;\n    }\n\n    public String getText() {\n        return text;\n    }\n\n    public void setText(String text) {\n        this.text = text;\n    }\n\n    public Runnable getRunnable() {\n        return runnable;\n    }\n\n    public void setRunnable(Runnable runnable) {\n        this.runnable = runnable;\n    }\n}\n\n\nFirst, we create an alertdialog using the custom_alert_dialog layout we created earlier. We also set the title and body, and define the button container ready for the next step. We also define the layoutparams to be used when the buttons are added to the container. The most important part of the parameters are the 1 at the very end, this gives every textview added the same weight, so that they will be stretched equally.\n\nprivate static void displayAlertDialog(Context context, String title, String body, DialogAction... actions) {\n    LayoutInflater inflater = LayoutInflater.from(context);\n    final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1);\n    final View inflatedLayout = inflater.inflate(R.layout.custom_alert_dialog, null);\n    final AlertDialog dialog = new AlertDialog.Builder(context).create();\n    dialog.setView(inflatedLayout);\n\n    ((TextView)inflatedLayout.findViewById(R.id.title)).setText(title);\n    ((TextView)inflatedLayout.findViewById(R.id.body)).setText(body);\n    final LinearLayout buttonContainer = (LinearLayout)inflatedLayout.findViewById(R.id.buttonContainer);\n\n\nNext, we loop through each DialogAction passed to displayAlertDialog(), set the button text, and set the onclick action to be the defined Runnable, and then closing the alertdialog. Each button is then added to the button container, and finally the alertdialog is displayed.\n\nfor (final DialogAction action : actions) {\n        TextView button = (TextView)inflater.inflate(R.layout.custom_alert_dialog_button, null);\n        button.setText(action.getText());\n        button.setOnClickListener(new View.OnClickListener() {\n            @Override\n            public void onClick(View view) {\n                action.getRunnable().run();\n                dialog.dismiss();\n            }\n        });\n        buttonContainer.addView(button, params);\n    }\n\n    dialog.show();\n}\n\n\nThat’s it! It’s a relatively simple concept, but allows a lot more flexibility and consistency between Android versions.\n\nExample\n\nAn example of actually displaying an alertdialog using this technique is below, it is called when the player runs out of items in the slots game Blacksmith Slots. In this instance 3 DialogActions are used, the first of which has no action inside the run() method, so just closes the alert dialog. Since we have access to the activity at this stage, the alertdialog buttons can easily perform actions on the activity, such as starting another activity.\n\npublic static void outOfItems(final Activity activity, final int itemTier, final int itemType) {\n    displayAlertDialog(activity, activity.getString(R.string.outOfItems), activity.getString(R.string.outOfItemsLong),\n            new DialogAction(activity.getString(R.string.lowerBet), new Runnable() {\n                @Override\n                public void run() {\n\n                }\n            }),\n            new DialogAction(activity.getString(R.string.exit), new Runnable() {\n                @Override\n                public void run() {\n                    activity.finish();\n                }\n            }),\n            new DialogAction(activity.getString(R.string.shop), new Runnable() {\n                @Override\n                public void run() {\n                    activity.startActivity(new Intent(activity, ShopActivity.class)\n                            .putExtra(\"tier\", itemTier)\n                            .putExtra(\"type\", itemType)\n                            .addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));\n                }\n            }));\n}\n\n\nThe Conclusion\n\nAlert dialogs are very easy to use, but can be tricky to customise. Using a custom layout allows full control over the dialog, and the code in this article can easily be expanded on to create more advanced functionality. It’s also worth noting that 9patch images should be used as a background for the button &amp; alertdialog layouts, as it allows the elements to resize without stretching.\n\nThe full gist of code used is available here.\n"
    } ,
  
    {
      "tags"     : "Barcode, Camera, Google Vision Library, Intents, QR Code, User Generated Content, ZXing",
      "title"    : "Importing Levels From QR Codes (Camera / File) in Android",
      "excerpt"  : "In a previous post, it was discussed how to export levels from an Android game (in this case Connect Quest) so that other players could play them. Now that they’re exported, we need to be able to import them again! This post will explain how to import QR codes either directly from the camera, or embedded within an image on the file system.\n",
      "url"      : "/android-importing-levels-from-qr-codes-camera-file/",
      "date"     : "Apr 14, 2017",
      "content"  : "In a previous post, it was discussed how to export levels from an Android game (in this case Connect Quest) so that other players could play them. Now that they’re exported, we need to be able to import them again! This post will explain how to import QR codes either directly from the camera, or embedded within an image on the file system.\n\nThe Solution\n\nCamera\n\nTo avoid including a barcode reader, camera display, orientation tracking, and requiring the camera permission, we offload this responsibility to an existing app that is present on many phones, Barcode Scanner by ZXing. Whilst there is a risk of the user not having this app installed, in my specific use case it wasn’t worth spending weeks reinventing the wheel for a little used feature. It is possible to embed ZXing and do the barcode scanning without a third party application.\n\nWhen launching the barcode scanner, we also inform it (via the SCAN_MODE intent data) that we’re looking for QR Codes, to avoid it looking for other unrelated formats. If the user doesn’t have the application installed, we can’t scan, so we redirect the user to the store page for the ZXing app, and inform them what is happening.\n\nThe following is set as the onClick action for an import button, the result will be received by onActivityResult, described later in this post.\n\npublic void importFromCamera(View v) {\n    try {\n        Intent intent = new Intent(\"com.google.zxing.client.android.SCAN\");\n        intent.putExtra(\"SCAN_MODE\", \"QR_CODE_MODE\");\n        startActivityForResult(intent, INTENT_CAMERA);\n    } catch (Exception e) {\n        Toast.makeText(this, R.string.error_no_barcode_scanner, Toast.LENGTH_SHORT).show();\n        Uri marketUri = Uri.parse(\"market://details?id=com.google.zxing.client.android\");\n        Intent marketIntent = new Intent(Intent.ACTION_VIEW, marketUri);\n        startActivity(marketIntent);\n    }\n}\n\n\nA video of this in action is embedded below. Note the quick scanning of the QR code, and how the data is immediately available for processing (level imported &amp; ready to play straight away).\n\n\n\nPhoto\n\nRetrieving a photo is a little more complex than live scanning a QR code, but it’s done without requiring another application. First, the onClick method of the import button is called, and passes the permission required (READ_EXTERNAL_STORAGE) and work to do (importFromFile()) to a runIfPossible function.\n\npublic void importFromFile(View v) {\n    PermissionHelper.runIfPossible(Manifest.permission.READ_EXTERNAL_STORAGE, new Runnable() {\n        @Override\n        public void run() {\n            importFromFile();\n        }\n    });\n}\n\n\nThis runIfPossible function utilises the very straightforward AllowMe library. First, it checks if the permission is granted already. If it is, then we can run the callback (work to do) we passed through, otherwise the permission needs to be gained.\n\npublic static void runIfPossible(final String permission, final Runnable callback) {\n    if (!AllowMe.isPermissionGranted(permission)) {\n        new AllowMe.Builder()\n                .setPermissions(permission)\n                .setCallback(new AllowMeCallback() {\n                    @Override\n                    public void onPermissionResult(int requestCode, PermissionResultSet result) {\n                        if (result.isGranted(permission)) {\n                            callback.run();\n                        }\n                    }\n                })\n                .request(123);\n    } else {\n        callback.run();\n    }\n}\n\n\nTo gain the permission, a standard Android permission request is displayed, where the user can choose to allow or deny the app access to external storage. If it is approved (result.isGranted()), then the callback is run. If they deny the permission, then nothing is done, since we don’t have the access we need. Note that the request code here is irrelevant, since there are no other request codes being used in this code area.\n\n\n\nThe importFromFile function that does the actual work is very simple, and just opens a native Android image picker. This allows the user to use an interface that is familiar to them to navigate their images, and eventually select one to send back to our activity.\n\n\nprivate void importFromFile() {\n    Intent intent = new Intent();\n    intent.setType(\"image/*\");\n    intent.setAction(Intent.ACTION_GET_CONTENT);\n    startActivityForResult(Intent.createChooser(intent, \"Select Picture\"), INTENT_FILE);\n}\n\n\nReceiving\n\nThe activity that launched the camera or file import tasks now needs to be notified that there is incoming data. This is done via onActivityResult, since both of the previous tasks used startActivityForResult, so will return data when they are completed (either cancelled, or found an image / QR code to import).\n\nThe INTENT_CAMERA and INTENT_FILE values are just constants we used when starting the data-retrieval actions, so that we know which is returning data. They can be any integer, they should be unique though. First, we check that the action wasn’t a cancellation using resultCode == RESULT_OK, then process the retrieved data (covered after code snippet).\n\nIf the puzzleString has data, and it is successfully imported (split up, sanity checked, and added to database), then perform any post-import actions required.\n\n@Override\npublic void onActivityResult(int requestCode, int resultCode, Intent data) {\n    super.onActivityResult(requestCode, resultCode, data);\n\n    if (resultCode == RESULT_OK) {\n        String puzzleString = \"\";\n        if (requestCode == INTENT_CAMERA) {\n            puzzleString = data.getStringExtra(\"SCAN_RESULT\");\n        } else if (requestCode == INTENT_FILE) {\n            try {\n                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData());\n                puzzleString = StorageHelper.readQRImage(this, bitmap);\n            } catch (Exception e) {\n                AlertHelper.error(this, AlertHelper.getError(AlertHelper.Error.FILE_IMPORT_FAIL));\n            }\n        }\n\n        if (!puzzleString.equals(\"\") &amp;&amp; PuzzleShareHelper.importPuzzleString(puzzleString, false)) {\n            GooglePlayHelper.UpdateEvent(Constants.EVENT_IMPORT_PUZZLE, 1);\n            AlertHelper.success(this, R.string.alert_puzzle_imported);\n            populatePuzzles();\n        } else if (requestCode == INTENT_CAMERA) {\n            AlertHelper.error(this, AlertHelper.getError(AlertHelper.Error.CAMERA_IMPORT_FAIL));\n        } else if (requestCode == INTENT_FILE) {\n            AlertHelper.error(this, AlertHelper.getError(AlertHelper.Error.FILE_IMPORT_FAIL));\n        }\n    }\n}\n\n\nThe ZXing barcode scanner returns the data as a string extra under the key SCAN_RESULT, so we just read that. Easy! The file reader unfortunately has more work to do. First of all it checks the bitmap can actually be read (to avoid misnamed extensions, deleted files, private files, etc), then calls readQRImage.\n\nInitially, ZXing was used for processing, however it was quite unreliable and regularly could not detect codes. As such, the Google Vision library was used instead. Using this library, we create a BarcodeDetector that is looking for QR codes, scan the image, then retrieve the first barcode found (there should only be one anyway!). The image\n\npublic static String readQRImage(Activity activity, Bitmap bitmap) {\n    String contents = \"\";\n\n    BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(activity)\n            .setBarcodeFormats(Barcode.QR_CODE)\n            .build();\n\n    SparseArray detectedBarcodes = barcodeDetector.detect(new Frame.Builder()\n            .setBitmap(bitmap)\n            .build());\n\n    if (detectedBarcodes.size() &gt; 0 &amp;&amp; detectedBarcodes.valueAt(0) != null) {\n        contents = detectedBarcodes.valueAt(0).rawValue;\n    }\n    return contents;\n}\n\n\nThe camera or file QR code has now been successfully read, the puzzle imported, and the user is ready to play it!\n\nThe Conclusion\n\nSupporting user created content can be a daunting task at first, but it’s worth the investment to increase engagement and allow the game a life of it’s own. Of course, if the app has the server resources to create a hosted content hub, that is superior, but offline distribution like this post describes is suitable for most smaller apps.\n\nWhilst offloading the camera barcode scanning to a third party app isn’t ideal, it was decided upon as the approach to prevent having to integrate camera APIs, and to increase reliability. The file import option is also far more likely to be used, as users are more likely to save a picture from the internet than to scan a live QR code. Additionally, the user could just take a photo and scan that if they were unwilling to install another app.\n\nHopefully this post about how Connect Quest handles level sharing has encouraged you to consider it for your next game, and use this guide as a starting point. Good luck!\n\nAs always, there is a Gist available for all code used in this post.\n"
    } ,
  
    {
      "tags"     : "QR Code, User Generated Content, ZXing, Java",
      "title"    : "Exporting Levels Into QR Codes Using ZXing",
      "excerpt"  : "Connect Quest is an android game where players rotate tiles to make a city flow. They also have the ability to create their own levels, and share them with other players. The data transfer method chosen was QR codes, since it was the most widely-used and compact method available.\n",
      "url"      : "/exporting-levels-into-qr-codes-using-zxing/",
      "date"     : "Apr 6, 2017",
      "content"  : "Connect Quest is an android game where players rotate tiles to make a city flow. They also have the ability to create their own levels, and share them with other players. The data transfer method chosen was QR codes, since it was the most widely-used and compact method available.\n\nThe Solution\n\nTo allow the easy transferring of data, card images could be generated from levels, which contained information about the map alongside the QR code. These could then be shared easily via any normal system. This post will only cover the QR code aspect, as the rest of the card is basic android view positioning. The popular ZXing library is used for QR code generation, due to its widespread usage and simple implementation.\n\n\n\nCreating String\n\nFirst, your level structure must be converted to a string. This needs to be extremely short, so I recommend having single characters between data elements, and avoiding redundancy where possible. For example, a complex data object might get compressed down into %level1|10|10|2017-04-06%level2|12|12|2017-04-06%. It’s also recommended to do some kind of obfuscation on this string, even if it’s just base64 encoding, as the players will see it when they import the level (covered in a future post).\n\nAn example implementation is below, but the data to be stored and the delimiters to use are very problem-specific.\n\npublic static String getPuzzleString(Puzzle puzzle) {\n    PuzzleCustom puzzleCustom = puzzle.getCustomData();\n    StringBuilder sb = new StringBuilder();\n    sb.append(puzzleCustom.getName()).append(sectionDelimiter)\n            .append(puzzleCustom.getDescription()).append(sectionDelimiter)\n            .append(puzzleCustom.getAuthor()).append(sectionDelimiter)\n            .append(puzzle.getParMoves()).append(sectionDelimiter)\n            .append(puzzle.getParTime()).append(sectionDelimiter);\n\n    List tiles = puzzle.getTiles();\n    for (Tile tile : tiles) {\n        sb.append(tile.getTileTypeId()).append(tileElementDelimiter)\n                .append(tile.getX()).append(tileElementDelimiter)\n                .append(tile.getY()).append(tileElementDelimiter)\n                .append(tile.getRotation()).append(tileDelimiter);\n    }\n    return sb.toString();\n}\n\nNext, the fillWithQrDrawable method is passed the view to populate, and the string that needs converting. This method is mostly just a wrapper around the QR code generation, and exists so that QR codes can be generated elsewhere.\n\npublic static void fillWithQrDrawable(ImageView imageView, String text) {\n    try {\n        Bitmap bitmap = generateQrCode(text);\n        imageView.setImageBitmap(bitmap);\n    } catch (WriterException e) {\n        e.printStackTrace();\n    }\n}\n\n\nCreating QR Code\n\nFinally, the actual QR code needs to be generated. This is a slightly modified version of a StackOverflow answer, further support / comments can be found there.\n\nFirst, a BitMatrix is created by passing the string to be encoded to MultiFormatWriter.encode(), along with the relatively arbitrary desired size. Additionally, two hints are provided to the encoder to modify the output somewhat:\n\n\n  The EncodeHintType.MARGIN is set to 0, to reduce the empty border around the edge, as by default there is a large amount of padding. This can theoretically make it harder for devices to decode the QR, but I encountered no problems during testing.\n  The EncodeHintType.ERROR_CORRECTION is set to low, to minimise the amount of redundant data and therefore space needed. Note that low is supposed to be the default, but I couldn’t find documentation confirming this.\n\n\nEvery element in the 2D BitMatrix array is then queried for boolean state, and converted into a more standard 1D int array. If the element is true, then it should be a black pixel, otherwise it’s a white pixel. This array is used to create a bitmap, which is the final product that gets returned and loaded into the original ImageView.\n\n\npublic final static int WHITE = 0xFFFFFFFF;\npublic final static int BLACK = 0xFF000000;\npublic final static int WIDTH = 400;\npublic final static int HEIGHT = 400;\nprivate static Bitmap generateQrCode(String str) throws WriterException {\n    BitMatrix result;\n    try {\n        Map hints = new EnumMap(EncodeHintType.class);\n        hints.put(EncodeHintType.MARGIN, 0);\n        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);\n        result = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);\n    } catch (IllegalArgumentException iae) {\n        // Unsupported format\n        return null;\n    }\n\n    int width = result.getWidth();\n    int height = result.getHeight();\n    int[] pixels = new int[width * height];\n    for (int y = 0; y &lt; height; y++) {\n        int offset = y * width;\n        for (int x = 0; x &gt; width; x++) {\n            pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;\n        }\n    }\n\n    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);\n    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);\n    return bitmap;\n}\n\n\nThe Conclusion\n\nThe implementation described here is extremely fast, and at it’s core is a wrapper around the extremely powerful ZXing library, so is very reliable. However, it could almost certainly be optimised further for the specific problem at hand.\n\nFor example, as the generated images are going to be shared digitally, very little error correction was needed. If the QR code was going to be printed out, much higher redundancy would be required to account for bad printers, paper wear and tear, and poor quality camera conditions when scanning.\n\nQR codes also happened to be the best format for this player-facing implementation, but if you have control over the scanning hardware, a more compact / uncommon format could be used. Additionally, considering the core of this post is a StackOverflow answer about an open source library, it really highlights the amazing benefits open source code provides.\n\nAll code snippets used in this post are available as a Gist, and Connect Quest is available on the Play Store.\n"
    } ,
  
    {
      "tags"     : "Formula, Levels, XP",
      "title"    : "Converting Levels Into XP & Vice Versa",
      "excerpt"  : "Many games (such as my own Pixel Blacksmith and Blacksmith Slots) contain an XP / level system, where performing actions will reward experience, and eventually new levels. These new levels often unlock new content, or provide currency, so keeping players incentivised without feeling like a “grind” is a tricky balance.\n",
      "url"      : "/converting-levels-into-xp-vice-versa/",
      "date"     : "Mar 1, 2017",
      "content"  : "Many games (such as my own Pixel Blacksmith and Blacksmith Slots) contain an XP / level system, where performing actions will reward experience, and eventually new levels. These new levels often unlock new content, or provide currency, so keeping players incentivised without feeling like a “grind” is a tricky balance.\n\nThe Solution\n\nFirst, come up with a basic formula to use for calculating the XP required for a level. The most common by far is (level/x)^y, with x affecting the amount of XP (lower values = more XP required per level), and y being how quickly the required xp per level should increase (higher values = larger gaps between levels).\n\nNext, make a spreadsheet where x and y can be quickly and easily modified, and the XP per level seen. Here is my spreadsheet, feel free to make a copy.\n\nAs an example, here’s a comparison of the XP required for levels using varying values of x and y. Note that using 2/3 for y is recommended, so that built in squaring / cubing functions can be used.\n\nExample 1: X: 0.07, Y: 2\n\nThis has a fairly quickly increasing amount of XP per level (y) and a large amount of XP (x), and is good for games where XP is relatively easy to gain.\n\n\n  \n    \n      Level\n      XP\n      Difference\n    \n  \n  \n    \n      0\n      0\n      0\n    \n    \n      1\n      204.0816327\n      204\n    \n    \n      2\n      816.3265306\n      612\n    \n    \n      3\n      1836.734694\n      1020\n    \n    \n      4\n      3265.306122\n      1429\n    \n    \n      5\n      5102.040816\n      1837\n    \n    \n      6\n      7346.938776\n      2245\n    \n    \n      7\n      10000\n      2653\n    \n    \n      8\n      13061.22449\n      3061\n    \n    \n      9\n      16530.61224\n      3469\n    \n    \n      10\n      20408.16327\n      3878\n    \n  \n\n\nExample 2: X: 0.3, Y: 2\n\nThis has a high value for x, so the amounts of XP required for a level up are very small. This would be good for a game where XP is relatively hard to obtain (e.g. requires collecting items). Note that the % increase in XP between levels 1 and 2 is the same as Example 1 (3x higher).\n\n\n  \n    \n      Level\n      XP\n      Difference\n    \n  \n  \n    \n      0\n      0\n      0\n    \n    \n      1\n      11.11111111\n      11\n    \n    \n      2\n      44.44444444\n      33\n    \n    \n      3\n      100\n      56\n    \n    \n      4\n      177.7777778\n      78\n    \n    \n      5\n      277.7777778\n      100\n    \n    \n      6\n      400\n      122\n    \n    \n      7\n      544.4444444\n      144\n    \n    \n      8\n      711.1111111\n      167\n    \n    \n      9\n      900\n      189\n    \n    \n      10\n      1111.111111\n      211\n    \n  \n\n\nExample 3: X: 0.07, Y: 3\n\nThis uses a different value for y than the other 2 examples, and as such the XP required rapidly increases. This would be used in a game where higher levels have significantly higher XP gaining potential (e.g. an incremental game).\n\n\n  \n    \n      Level\n      XP\n      Difference\n    \n  \n  \n    \n      0\n      0\n      0\n    \n    \n      1\n      2915.451895\n      2915\n    \n    \n      2\n      23323.61516\n      20408\n    \n    \n      3\n      78717.20117\n      55394\n    \n    \n      4\n      186588.9213\n      107872\n    \n    \n      5\n      364431.4869\n      177843\n    \n    \n      6\n      629737.6093\n      265306\n    \n    \n      7\n      1000000\n      370262\n    \n    \n      8\n      1492711.37\n      492711\n    \n    \n      9\n      2125364.431\n      632653\n    \n    \n      10\n      2915451.895\n      790087\n    \n  \n\n\nUsing The Formula\n\nNow that we have a formula for XP required for any level (using Example 1: XP = (level/0.07)^2), we also need to know the current level based on XP. Inverting the formula gives us level = 0.07 * √XP. The second formula can be harder to implement due to requiring “nth root of”, hence why using a value of 2/3 is recommended.\n\nXP and levels can now be converted easily and efficiently, without requiring any lengthy formulas. However, how useful the formula will be depends entirely on how well the x and y values are tuned for the specific use case. Get it wrong, and players will power through content or complain about being too grindy, get it right and they’ll never mention it!\n\nThe Conclusion\n\nLevels are an extremely common way of rewarding consistent players, and providing an incentive to continue playing the game, or to replay older content. Balancing the formula is extremely important, and the simplicity of the formula described in this post means that consistent complaints of level ups being too frequent or too infrequent can be fixed by changing a single variable.\n\nIt is applicable to pretty much any game on any platform, but is especially useful in mobile applications, where processing power can be more limited, and player attention harder to keep.\n\nA gist of a Java implementation of converting between XP &amp; levels, as well as calculating current % progress towards next level is available here.\n"
    } ,
  
    {
      "tags"     : "Formula, Tiles",
      "title"    : "Calculating Weapon Damage Using Ideal Ranges",
      "excerpt"  : "Whilst building a turn based strategy shooter, weapons needed to have “ideal ranges”. For example, a melee weapon should only work from 1 tile away, a shotgun should prefer short ranges, a sniper rifle should prefer long ranges, etc. The non-melee weapons should still work outside of their ideal range, but with reduced damage.\n",
      "url"      : "/calculating-weapon-damage-with-ideal-ranges/",
      "date"     : "Feb 19, 2017",
      "content"  : "Whilst building a turn based strategy shooter, weapons needed to have “ideal ranges”. For example, a melee weapon should only work from 1 tile away, a shotgun should prefer short ranges, a sniper rifle should prefer long ranges, etc. The non-melee weapons should still work outside of their ideal range, but with reduced damage.\n\nThe Solution\n\nFirst, the weapon ranges must be calculated, then whether the target distance is inside this range or not, and finally calculate the total damage based on the previous value.\n\nThese are the minimum and maximum ranges for each type of weapon, along with how numbers are included in this range (note that this is an inclusive range, so includes the minimum and maximum values):\n\n\n  \n    \n      Weapon Type\n      Minimum\n      Maximum\n      Range\n    \n  \n  \n    \n      Melee\n      1\n      1\n      1\n    \n    \n      Short\n      2\n      4\n      3\n    \n    \n      Medium\n      5\n      7\n      3\n    \n    \n      Long\n      8\n      15\n      8\n    \n  \n\n\nFor this post a consistent set of test values will be used: 1, 2, 3, 5, 8, and 10 tiles away, providing a range of values that fall in and out of all weapon’s ideal ranges.\n\nTiles Out Of Range\n\nFirst, if our test value is within a weapon’s ideal range, then it is 0 outside of ideal range. Alternatively, get the minimum absolute value of the difference between the value and the minimum and maximum bounds of the range. That was a bit of a mouthful, an example should clarify!\n\nIn this example the long weapon type (range 8-15 tiles) will be firing at a target 5 tiles away. 5 is -3 away from the minimum, 8, and -10 away from the maximum, 15. The absolute value of these two is 3 and 10, the minimum of which is 3. Via this rather convoluted process, the fact that the target is 3 tiles out of range is now known.\n\nThe below table shows a full matrix of tiles out of range for each weapon type. The example above is shown in red.\n\n\n  \n    \n       \n      1\n      2\n      3\n      5\n      8\n      10\n    \n  \n  \n    \n      Melee\n      0\n      1\n      2\n      4\n      7\n      9\n    \n    \n      Short\n      1\n      0\n      0\n      1\n      4\n      6\n    \n    \n      Medium\n      4\n      3\n      2\n      0\n      1\n      3\n    \n    \n      Long\n      7\n      6\n      5\n      3\n      0\n      0\n    \n  \n\n\nDamage Multiplier\n\nNext, the damage multiplier will be calculated, based on how far out of ideal range the target is. This is a simpler formula than before, being 1 - (tilesOutOfRange / weaponRange). Using the same example situation as before, the calculation will be 1 - (5 / 8) = 0.375. If a negative damage multiplier is calculated, then 0 will be used instead.\n\nAs before, the below table shows a full matrix of damage multiplier for each weapon type based on distance away, with the example highlighted in red. Note that values are rounded to 2 decimal places for visual clarity, so the example becomes 0.38.\n\n\n  \n    \n       \n      1\n      2\n      3\n      5\n      8\n      10\n    \n  \n  \n    \n      Melee\n      1\n      0\n      0\n      0\n      0\n      0\n    \n    \n      Short\n      0.67\n      1\n      1\n      0.67\n      0\n      0\n    \n    \n      Medium\n      0\n      0\n      0.33\n      1\n      0.67\n      0\n    \n    \n      Long\n      0.13\n      0.25\n      0.38\n      0.63\n      1\n      1\n    \n  \n\n\nDamage\n\nNow, the final step! Simply multiply the weapon’s base damage by the multiplier to calculate the actual weapon damage dealt. For such a basic calculation no table is needed, but if the sample long distance weapon is assumed to deal 100 damage, we end up with the conclusion that the weapon will deal 38 damage to a target 5 tiles away. Melee weapons are also only effective 1 tile away.\n\nMisc\n\nBelow I’ve quoted my rough notes for the formula, as a more concise but less clear version of the calculations above:\n\n\n  Weapon Range = (Maximum – Minimum) + 1.\nTiles Out Of Range = If in range, then 0. Otherwise, the minimum (absolute) distance between the tile and the minimum or maximum.\nDamage Multiplier = (1 – (Tiles Out Of Range / Weapon Range).\nDamage = If damage multiplier &gt; 0, then base damage * damage multiplier, otherwise 0.\n\n\nAdditionally, a Java implementation is available as a Gist, which may be easier to understand.\n\nThe Conclusion\n\nWhilst the actual use case is fairly niche, this post should indicate why a generic formula is often the preferred approach instead of hardcoding lookup tables. With the approach taken, adding a new weapon type or dynamically adjusting a weapon’s range is very easy, and the damage is quickly calculated.\n\nThe formula may be useful for anyone needing to calculate values that need to drop off outside of a specific range at a varying rate, based on the size of the range.\n\nAdditionally, this was a “iteratively created” formula, where I essentially played with variables in Excel / Google Sheets until I got values that matched what I wanted to see. As such, I strongly suspect some steps are inefficient, particularly when calculating how far out of range a target is.\n"
    } ,
  
    {
      "tags"     : "MediaPlayer, Sound Effects, Java",
      "title"    : "Playing Random Sounds on Android",
      "excerpt"  : "During various events in Pixel Blacksmith, a sound effect needs to play. There is more than one possible sound effect per event, so one needs to be randomly picked each time.\n",
      "url"      : "/android-playing-random-sounds/",
      "date"     : "Feb 3, 2017",
      "content"  : "During various events in Pixel Blacksmith, a sound effect needs to play. There is more than one possible sound effect per event, so one needs to be randomly picked each time.\n\nThe Solution\n\nFirst, arrays of references to all possible sound files (stored in .ogg / .mp3 / .wav format in src/main/res/raw) are created. They can be final and static, since they’re never going to change, but need to be public so that the rest of the application can refer to them.\n\npublic static final int[] enchantingSounds = {R.raw.enchant1};\npublic static final int[] sellingSounds = {R.raw.sell1, R.raw.sell2};\npublic static final int[] smithingSounds = {R.raw.smith1, R.raw.smith2, R.raw.smith3};\npublic static final int[] walkingSounds = {R.raw.footsteps1};\npublic static final int[] transitionSounds = {R.raw.slide1, R.raw.slide2, R.raw.slide3};\n\n\nWhen a sound-triggering event is played, the relevant reference array is passed to a playSound() function from an activity, using SoundHelper.playSound(this, SoundHelper.transitionSounds).\n\nThe playSound() function selects an item from the array at random by picking a number between zero and the length of the array, then selecting that element of the zero-indexed array. Now that a specific sound file reference has been determined, this is passed to a more specific playSound().\n\n// If an array is passed, pick one at random to play.\npublic static void playSound(Context context, int[] sounds) {\n    int soundID = sounds[new Random().nextInt(sounds.length)];\n    playSound(context, soundID);\n}\n\n\nNow that the specific file has been identified, a check is performed to see if the player has sounds enabled. If they don’t, they won’t be happy if the sound plays! If they do, a new MediaPlayer is created and started. This is wrapped in a try/catch as I’ve personally found media players to be somewhat error prone, despite being a core Android building block.\n\nprivate static void playSound(Context context, int soundID) {\n    // Only play if the user has sounds enabled.\n    if (Setting.getSafeBoolean(Constants.SETTING_SOUNDS)) {\n        try {\n            MediaPlayer mediaPlayer = MediaPlayer.create(context, soundID);\n            mediaPlayer.start();\n        } catch (Exception e) {\n            Log.d(\"Blacksmith\", e.toString());\n        }\n    }\n}\n\n\nThe Conclusion\n\nThis solution works well for quick and simple playing of short sound effects. However, sound effects can overlap, so it would not be suitable for more complex sound effects such as an enemy boss making specific noises per attack. It’s very reliable however, and even short sound effects can help add character to the game.\n\nAdditionally, a large number of free sound samples are available from FreeSound, and I highly recommend taking a look if a specific sound sample is wanted.\n\nA full Gist of this solution is available here.\n"
    } ,
  
    {
      "tags"     : "Randomness, SQLite, Weighting, Java",
      "title"    : "Selecting A Weighted Random Item From A List in Android",
      "excerpt"  : "In Pixel Blacksmith, visitors arrive in the shop and have demands that need fulfilling. The visitors are mostly random, but each visitor is weighted to appear more or less frequently, to allow for rarer visitors. These weighted probabilities also need to be modifiable, to add seasonal visitors etc.\n",
      "url"      : "/android-selecting-a-weighted-random-item-from-a-list/",
      "date"     : "Jan 27, 2017",
      "content"  : "In Pixel Blacksmith, visitors arrive in the shop and have demands that need fulfilling. The visitors are mostly random, but each visitor is weighted to appear more or less frequently, to allow for rarer visitors. These weighted probabilities also need to be modifiable, to add seasonal visitors etc.\n\nThe Solution\n\nFirst, a list of all candidates must be created. The SQL in the example below is mostly irrelevant, it selected all visitors except ones that are currently present, it can be replaced by any other technique that ends up with a list of items.\n\nprivate static Visitor_Type selectVisitorType() {\n    Visitor_Type visitor = new Visitor_Type();\n\n    List visitorTypes = Visitor_Type.findWithQuery(Visitor_Type.class,\n            \"SELECT * FROM VisitorType WHERE visitor_id NOT IN (SELECT type FROM Visitor)\");\n\n\nMost importantly, every item in the list that is being selected from must have a weighting, determining how likely they are to be selected. The actual values are irrelevant, all that matters is their relation to each other. For example, a weighting of 20 is twice as likely to be selected as a weighting of 10.\n\nNext, the total weighting must be calculated. This is a simple case of iterating through the list and summing the weights.\n\n// Work out the total weighting.\ndouble totalWeighting = 0.0;\nfor (Visitor_Type type : visitorTypes) {\n    totalWeighting += type.getWeighting();\n}\n\n\nAfter we have a total weighting, a number has to be selected between 0 and the total weighting. Due to Math.random() returning a double between 0 and 1, this is just a case of multiplying the result by the total weighting.\n\nTo explain how this works, imagine a list of 2 items, one with a weight of 10, and one with a weight of 30, giving a total weight of 40. If a number between 0-10 is picked, the first item will be selected, but if the number is in the larger range of 11-40, the second item will be picked. This effectively makes the second item 3x more likely to be selected, due to the ratio between 10 and 30.\n\n// Generate a number between 0 and total probability.\ndouble randomNumber = Math.random() * totalWeighting;\n\n\nNow that a number has been selected, the list has to be walked through, keeping track of the running total. If after adding the current item’s weighting the total is above the random number, then the random number is in the current item’s range, so has been selected. The selected item is then returned.\n\n    // Use the random number to select a visitor type.\n    double probabilityIterator = 0.0;\n    for (Visitor_Type type : visitorTypes) {\n        probabilityIterator += type.getWeighting();\n        if (probabilityIterator &gt;= randomNumber) {\n            visitor = type;\n            break;\n        }\n    }\n    return visitor;\n}\n\n\nThe Conclusion\n\nWhilst a simple little function, the ability to select a weighted item from a list is pretty important if there’s any kind of loot / spawn mechanics in a game. The code isn’t dependant on any type of object or ORM, so is applicable to most scenarios.\n\nA future improvement would be creating a generic function that receives a list of items that implement .getWeighting(), then returns a single item of that type. This would ensure the same code could be reused for multiple selections.\n\nA Gist of the full function (and a Kotlin updated version) is available here.\n\nPixel Blacksmith is a free game developed by myself, it’s featured here because I know the code well!\n"
    } ,
  
    {
      "tags"     : "Display Pixels, DisplayMetrics, dp, Java",
      "title"    : "Converting Display Pixels (dp) To Real Pixels",
      "excerpt"  : "Occasionally whilst developing a UI in Android, padding will have to be set programmatically, this usually happens when padding varies according to the number of items on screen. These values must be set in pixels, but the size of a pixel will vary massively, according to the density of the screen (for example, 2 1920px by 1080px and 192px by 108px screens may be the same physical size, but the former will have 10 times more pixels in any given centimetre). As such, display pixels (essentially a unit that aims to avoid this issue) must be used, however these values need converting into real pixels.\n",
      "url"      : "/android-converting-display-pixels-dp-to-real-pixels/",
      "date"     : "Jan 24, 2017",
      "content"  : "Occasionally whilst developing a UI in Android, padding will have to be set programmatically, this usually happens when padding varies according to the number of items on screen. These values must be set in pixels, but the size of a pixel will vary massively, according to the density of the screen (for example, 2 1920px by 1080px and 192px by 108px screens may be the same physical size, but the former will have 10 times more pixels in any given centimetre). As such, display pixels (essentially a unit that aims to avoid this issue) must be used, however these values need converting into real pixels.\n\nThe Solution\n\nFirst the density of the screen must be calculated, using the densityDpi in DisplayMetrics. Once we have that, we can work out how many real pixels one display pixel equals. To do this, the device’s DPI is divided by the default density that all other densities are worked out from (160).\n\npublic int convertDpToPixel(float dp) {\n    DisplayMetrics metrics = context.getResources().getDisplayMetrics();\n    float px = dp * (metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);\n    return (int) px;\n}\n\n\nOnce we have the number of pixels for a single display pixel, it is multiplied by the number of display pixels that need converting, and the real pixel value is now known. This can then be assigned as padding.\n\nint yPadding = convertDpToPixel(4);\nint xPadding = convertDpToPixel(6.5f);\nvisitorImage.setPadding(xPadding, yPadding, xPadding, yPadding);\n\n\nThe Conclusion\n\nThis is an excellent example of the occasional simple task that comes up during Android development with a somewhat counterintuitive solution. This utility method has been in most of my Android projects in some place or another, and has been extremely useful. Note that a contextless version is available by replacing line 564 with:\n\nDisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();\n\n\nFurther reading is available in the same question as the original code.\n\nNote: Header image via StackOverflow.\n"
    } ,
  
    {
      "tags"     : "ColorFilter, Colours, PorterDuff, Tint, Java",
      "title"    : "Tinting Item Colour According To Status in Android",
      "excerpt"  : "Pixel Blacksmith is an Android game where players craft and sell items to visitors, in order to make a profit to buy upgrades / more resources. These items can be enchanted with gems, and the item’s image needs to be tinted the gem’s colour to reflect this.\n",
      "url"      : "/android-tinting-item-colour-according-to-status/",
      "date"     : "Jan 21, 2017",
      "content"  : "Pixel Blacksmith is an Android game where players craft and sell items to visitors, in order to make a profit to buy upgrades / more resources. These items can be enchanted with gems, and the item’s image needs to be tinted the gem’s colour to reflect this.\n\nThe Solution\n\nTo modify the item’s colour (whilst only affecting the transparent pixels), we’ll be using the MULTIPLY color filter option. It can be hard to predict the outcome a specific colour code will have when applied to the drawables, so it’s recommended to try out 5-6 and choose one which has the desired effect.\n\nDefining Colours\n\nFirst, the hex codes of the desired colours were found via trial and error, and saved in the colors.xml file.\n\n&lt;color name=\"redOverlay\"&gt;#ff7777&lt;/color&gt;\n&lt;color name=\"blueOverlay\"&gt;#9cb4fc&lt;/color&gt;\n&lt;color name=\"greenOverlay\"&gt;#8abc84&lt;/color&gt;\n&lt;color name=\"whiteOverlay\"&gt;#e2e2e2&lt;/color&gt;\n&lt;color name=\"blackOverlay\"&gt;#3d3d3d&lt;/color&gt;\n&lt;color name=\"purpleOverlay\"&gt;#b041ba&lt;/color&gt;\n&lt;color name=\"yellowOverlay\"&gt;#e2df0b&lt;/color&gt;\n\n\nApplying Colours\n\nFor (albeit extremely minor, possibly non-existent) performance reasons, a switch statement is used instead of a large if / else. The item’s state (i.e. the colour it needs tinting) is checked against the list of states, and the correct colour is applied. The MULTIPLY porterduff mode is used. The technicalities of this aren’t necessary to know, but a reference image is very useful (source: Softwyer). Essentially, multiple merges the two resources, in this case the item image and the colour overlay, but only the pixels where the first resource isn’t fully transparent.\n\nimageResource is the item drawable to be modified. If no coloured state is identified, any existing colour filters are cleared, in case they’ve somehow got attached erroneously earlier on.\n\nswitch (itemState) {\n    case Constants.STATE_RED: imageResource.setColorFilter(ContextCompat.getColor(context, R.color.redOverlay), PorterDuff.Mode.MULTIPLY);\n        break;\n    case Constants.STATE_BLUE: imageResource.setColorFilter(ContextCompat.getColor(context, R.color.blueOverlay), PorterDuff.Mode.MULTIPLY);\n        break;\n    case Constants.STATE_GREEN: imageResource.setColorFilter(ContextCompat.getColor(context, R.color.greenOverlay), PorterDuff.Mode.MULTIPLY);\n        break;\n    case Constants.STATE_WHITE: imageResource.setColorFilter(ContextCompat.getColor(context, R.color.whiteOverlay), PorterDuff.Mode.MULTIPLY);\n        break;\n    case Constants.STATE_BLACK: imageResource.setColorFilter(ContextCompat.getColor(context, R.color.blackOverlay), PorterDuff.Mode.MULTIPLY);\n        break;\n    case Constants.STATE_PURPLE: imageResource.setColorFilter(ContextCompat.getColor(context, R.color.purpleOverlay), PorterDuff.Mode.MULTIPLY);\n        break;\n    case Constants.STATE_YELLOW: imageResource.setColorFilter(ContextCompat.getColor(context, R.color.yellowOverlay), PorterDuff.Mode.MULTIPLY);\n        break;\n    default: imageResource.clearColorFilter();\n        break;\n}\n\n\nNote that ContextCompat.getColor(context, id) is used to get the resolved colour instead of the very common, but deprecated, context.getResources().getColor(id). The latter method is extremely widespread, so unlikely to ever actually be removed, but it’s still always worth avoiding deprecated methods, to cut down on future maintenance.\n\nThe Conclusion\n\nWhilst providing a visual representation of the item’s state is a minor UI change, it helps reinforce the differences between items, and make the game’s items seem more varied. Identifying the colour filter mode and colour codes to use are rather dull exercises in trial and error, but the final effect is very effective.\n\nTinting a drawable with a colour is a common requirement in apps, helping to cut down on the number of unique drawables needed. This is much easier if the drawable is a single colour, specifically white. Below, the difference in effect between an ideal item (mostly white) and an imperfect one (2 strong colours, green and gold). The effect is much more obvious in the first, although still noticeable in the second.\n\n\n  \n    \n      Swords\n      Helmets\n    \n  \n  \n    \n      \n      \n    \n  \n\n"
    } ,
  
    {
      "tags"     : "Asynchronous, Database, ORM, Patches, SugarORM, Java",
      "title"    : "Asynchronous ORM Database Install in Android",
      "excerpt"  : "Many apps need to ship with a local database, and many apps also use a ORM to handle their database actions (I personally use and recommend Sugar). Tying together these two approaches requires some sort of compromise, often manually copying a SQLite database around the device’s filesystem.\n",
      "url"      : "/android-asynchronous-orm-database-install/",
      "date"     : "Jan 12, 2017",
      "content"  : "Many apps need to ship with a local database, and many apps also use a ORM to handle their database actions (I personally use and recommend Sugar). Tying together these two approaches requires some sort of compromise, often manually copying a SQLite database around the device’s filesystem.\n\nInstead for City Flow a different approach was decided: Installing the database on first run, providing progress updates to the user.\n\nThe Solution\n\nThe core part of the solution will be the AsyncTask described in an earlier article about asynchronous map generation. We’ll be starting an asynchronous task on first start, which will be reporting progress back to the progress bar and text on screen. In addition, we’ll be using ORM-specific techniques to actually save the new data, however they are common to almost every ORM.\n\nPreparing The Installer\n\nA separate PatchHelper class is used to handle the initial database install and subsequent patches. This is then called every time the app starts, in case any new databases patches are available. The app’s main activity creates a new PatchHelper instance (passing itself), then starts the AsyncTask.\n\n    new PatchHelper(this).execute();\n\n\nIn the PatchHelper constructor, we find the install text and progress bar from the calling activity so that we can update them during installation. These are just a TextView and a ProgressBar, the XML of which can be viewed at this Gist.\n\npublic class PatchHelper extends AsyncTask {\n    public final static int NO_DATABASE = 0;\n    public final static int V1_0_0 = 1;\n    private Activity activity;\n    private TextView progressText;\n    private ProgressBar progressBar; \n\n    public PatchHelper(Activity activity) {\n        this.activity = activity;\n        this.progressText = (TextView) activity.findViewById(R.id.progressText);\n        this.progressBar = (ProgressBar) activity.findViewById(R.id.progressBar);\n}\n\n\nStarting The Installer\n\nShared preferences are used to store the current database version. It’s very reliable, and we aren’t concerned about the user modifying this value if they’re rooted, so security is a non-issue.\n\nIf the current database version is non-existent, or set to NO_DATABASE(0), then the initial database install needs to be performed, and the new database version saved. Otherwise, just return, since no install is needed.\n\n@Override\nprotected String doInBackground(String... params) {\n    SharedPreferences prefs = activity.getSharedPreferences(\"uk.co.jakelee.cityflow\", MODE_PRIVATE);\n\n    if (prefs.getInt(\"databaseVersion\", PatchHelper.NO_DATABASE) &amp;lt;= PatchHelper.NO_DATABASE) {\n        createDatabase();\n        prefs.edit().putInt(\"databaseVersion\", PatchHelper.V1_0_0).apply();\n    }\n    return \"\";\n}\n\n\nPerforming The Install\n\nThe overarching createDatabase() calls 2 types of methods repeatedly, one to update the user, the other to actually perform the action.\n\nprivate void createDatabase() {\n    setProgress(\"Achievements\", 0);\n    createAchievement();\n    setProgress(\"Backgrounds\", 3);\n    createBackground();\n    --- many more similar lines clipped ---\n}\n\n\nTwo parameters are passed to setProgress(), the name of the current item, and the percentage of progress made. The percentage progress is fixed in this implementation based on usual installation times.\n\nsetProgress() updates the progress bar’s value, and passes the current item text onto publishProgress(). Somewhat confusingly, calling publishProgress triggers onProgressUpdate, which updates the progress text’s value. Note that multiple strings could very easily be passed.\n\nprivate void setProgress(String currentTask, int percentage) {\n    if (progressText != null &amp;&amp; progressBar != null) {\n        publishProgress(currentTask);\n        progressBar.setProgress(percentage);\n    }\n}\n\n@Override\nprotected void onProgressUpdate(String... values) {\n    progressText.setText(\"Installing:\\n\" + values[0]);\n}\n\n\nThe actual creation methods are very simple, and will be ORM specific. For Sugar ORM, the most efficient way to bulk-add records is to create a List of them, then pass the whole set to saveInTx(), where they will all be added very quickly (a few hundred records a second).\n\nprivate void createAchievement() {\n    List achievements = new ArrayList();\n    achievements.add(new Achievement(\"An achievement\");\n    achievements.add(new Achievement(\"Another achievement\"));\n    Achievement.saveInTx(achievements);\n}\n\n\nTidying Up\n\nFinally, the “progress” container is hidden, and the normal main menu is displayed. Included below for completeness, but hopefully it should be pretty obvious!\n\n    progressWrapper.setVisibility(View.GONE);\n    mainMenuWrapper.setVisibility(View.VISIBLE);\n\n\nThe Conclusion\n\nWhilst the actual installation is ORM specific, the overall mechanism of installing is applicable regardless of ORM, and even applicable to non-database background installations.\n\nAdditionally, it’s worth pointing out that an asynchronous database installation on first launch isn’t necessarily the best implementation for all use cases. If there is a very large amount of data for example, it may be more efficient to copy the database on launch, synchronise it from a remote server, or have a small “default” database replaced later on during a sync.\n"
    } ,
  
    {
      "tags"     : "DisplayMetrics, Isometric Tiles, Zoom Level, Java",
      "title"    : "Positioning Isometric Tiles & Displaying Levels At Optimum Zoom in Android",
      "excerpt"  : "City Flow is an Android game where players must rotate puzzle tiles until all flows (rivers, paths, etc) match up. Players can play existing levels, or create their own in a level editor. They can zoom in, out, and pan, so as to navigate larger puzzles easily. Whilst playing a level players are on a time limit, so ensuring all of the puzzle is on screen to begin with is very important to ensure the player doesn’t become frustrated having to initially get the puzzle in a good position.\n",
      "url"      : "/android-positioning-isometric-tiles-displaying-levels-at-optimum-zoom/",
      "date"     : "Jan 9, 2017",
      "content"  : "City Flow is an Android game where players must rotate puzzle tiles until all flows (rivers, paths, etc) match up. Players can play existing levels, or create their own in a level editor. They can zoom in, out, and pan, so as to navigate larger puzzles easily. Whilst playing a level players are on a time limit, so ensuring all of the puzzle is on screen to begin with is very important to ensure the player doesn’t become frustrated having to initially get the puzzle in a good position.\n\nThe Solution\n\nTo properly display the puzzle, we first need to know the zoom level (referred to as scale factor) for the X and Y axis, then use the lowest one, and try to place the puzzle in the middle of the screen.\n\nCalculating Optimum Zoom\n\nThe setupTileDisplay() function takes:\n\n\n  PuzzleDisplay (an interface of Activity, just with an extra function, not needed for this example)\n  The list of tiles to display\n  The area the tiles will be placed into (ZoomableViewGroup is originally from here)\n  The selected tile, selected tile imageview, and whether or not we’re in the editor. This are implementation specific, and not necessary.\n\n\npublic TileDisplaySetup setupTileDisplay(PuzzleDisplayer puzzleDisplayer, List tiles, ZoomableViewGroup tileContainer, Tile selectedTile, ImageView selectedTileImage, boolean isEditor) {\n    tileContainer.removeAllViews();\n\n    Setting minimumMillisForDrag = Setting.get(Constants.SETTING_MINIMUM_MILLIS_DRAG);\n    int dragDelay = minimumMillisForDrag != null ? minimumMillisForDrag.getIntValue() : 200;\n    Pair maxXY = TileHelper.getMaxXY(tiles);\n\n    DisplayValues displayValues = getDisplayValues(puzzleDisplayer.getActivity(), maxXY.first + 1, maxXY.second + 1);\n\n\nThe drag related code is to do with panning the ZoomableViewGroup. The first relevant line is 277, where we call a small helper function that loops through the list of tiles to work out the total puzzle size. This is used later.\n\nThe bulk of the actual logic happens inside getDisplayValues():\n\npublic DisplayValues getDisplayValues(Activity activity, int xTiles, int yTiles) {\n    DisplayMetrics displayMetrics = getSizes(activity);\n    int screenHeight = displayMetrics.heightPixels;\n    int screenWidth = displayMetrics.widthPixels;\n\n    double totalTilesAmount = (xTiles + yTiles) / 2.0;\n    int puzzleHeight = (int) (totalTilesAmount * getTileHeight());\n    int puzzleWidth = (int) (totalTilesAmount * getTileWidth());\n\n    float xZoomFactor = screenWidth / (float) (puzzleWidth);\n    float yZoomFactor = (screenHeight / (float) (puzzleHeight)) / 2;\n    float zoomFactor = Math.min(xZoomFactor, yZoomFactor);\n\n    int offset = puzzleHeight / 2;\n    return new DisplayValues(zoomFactor, offset, yZoomFactor &amp;lt; xZoomFactor);\n}\n\n\nFirst, we get the screen size as DisplayMetrics, since we’ll need that to work out what we can fit on it.\n\nNext, we work out how tall the puzzle is. Since my puzzle tiles aren’t perfectly square, and I’m using an isometric perspective, both the height and width are required to calculate the puzzle width or height. For example, if the puzzle has one more tile on the X axis, it’ll be 0.5 tiles wider, and 0.5 tiles taller (since half will overlap existing tiles).\n\ngetTileHeight() and getTileWidth(), convert the fixed dp (display pixels) into actual pixels, based on screen density. Again, a small helper function is used for conversion.\n\nNow we know how screen / puzzle width / height. To calculate the highest possible zoom factor whilst still fitting all of the puzzle on the screen, we calculate the best zoom factor for width and height, then take the minimum.\n\nHaving trouble visualising all these widths and heights? Here’s an annotated in-game screenshot, with all mentioned values:\n\n\n\nWe return the optimum zoom factor, how much we should offset the puzzle by, and a quick check of whether the puzzle is going to have space above it or left of it. This is used shortly to calculate where to add an offset to centre the puzzle.\n\nApplying Optimum Zoom\n\nNow that we know the ideal zoom level, we just need to actually apply it to the tiles, by looping through each tile in the list and performing some calculations.\n\nfloat optimumScale = displayValues.getZoomFactor();\n\nint topOffset = displayValues.isLeftOffset() ? 0 : displayValues.getOffset();\nint leftOffset = displayValues.isLeftOffset() ? displayValues.getOffset() : 0;\n\ntileContainer.setScaleFactor(optimumScale, true);\ntileContainer.removeAllViews();\nfor (final Tile tile : tiles) {\n    if (!puzzleDisplayer.displayEmptyTile() &amp;amp;&amp;amp; tile.getTileTypeId() == Constants.TILE_EMPTY) {\n        continue;\n    }\n\n    ZoomableViewGroup.LayoutParams layoutParams = new ZoomableViewGroup.LayoutParams(ZoomableViewGroup.LayoutParams.WRAP_CONTENT, ZoomableViewGroup.LayoutParams.WRAP_CONTENT);\n    int leftPadding = leftOffset + (tile.getY() + tile.getX()) * (getTileWidth() / 2);\n    int topPadding = topOffset + (tile.getX() + maxXY.second - tile.getY()) * (getTileHeight() / 2);\n    layoutParams.setMargins(leftPadding, topPadding, 0, 0);\n\n    int drawableId = getTileDrawableId(puzzleDisplayer.getActivity(), tile.getTileTypeId(), tile.getRotation());\n    ImageView image = createTileImageView(puzzleDisplayer, tile, drawableId, dragDelay);\n\n\nFrom the boolean parameter passed back from getDisplayValues(), we know whether the offset calculated should be applied to the top or left of the puzzle.\n\nCity Flow has the concept of “empty” tiles, which are essentially invisible tiles. If we encounter one of those, and the activity we’re displaying the puzzle on doesn’t want to see them, just skip this tile.\n\nThe left and top padding calculations are the key to laying out the puzzle. As mentioned before, every tile’s x and y on-screen position both depend on the tile’s x and y order. Using the example before, if a tile is added on the Y axis (top left – bottom right), it will be half a tile height lower than the previous tile, and half a tile width further over to the right. This leads to quite a complex calculation for positioning.\n\nOnce we know the margins we want to give the individual tile, we make the imageview and populate it with the correct tile in createTileImageView(). This isn’t necessary for this example.\n\nFinally, we return the selected tile imageview for future reference, and the optimum puzzle scale (inside a basic data structure object TileDisplaySetup(). This is used by custom puzzles in order to take a screenshot of the puzzle ready for sharing, but that’s another article!\n\n    --- snipped lines that handle displaying a tile as selected ---\n\n        tileContainer.addView(image, layoutParams);\n    }\n\n    return new TileDisplaySetup(selectedTileImage, optimumScale);\n}\n\n\nThe Conclusion\n\nFitting all of a puzzle on-screen is such a fundamental part of game design that it’s easy to forget it even needs to be done. Whilst I’m sure I’ve somewhat reinvented the wheel with my calculations of positioning, I’ve enjoyed the process of figuring out the maths behind it. The calculations in terms of X and Y and how they relate to the overall positioning are definitely applicable to most games. Luckily, most engines likely have something similar to this already implemented.\n\nIn terms of efficiency, the repeated calls to DisplayMetrics() can’t be ideal. However, figuring out the positions for even large (15×15) puzzles is always instant, the bottleneck is in loading the tile images from storage.\n\nThe core code used in this article is available on this gist, whilst the helper functions are available on this one.\n\nDisclaimer: I wrote City Flow, I’m featuring it here because I know the codebase very well!\n"
    } ,
  
    {
      "tags"     : "Algorithm, Isometric Tiles, Map Generation, Java",
      "title"    : "Asynchronous Map Generator for Android",
      "excerpt"  : "City Flow is an Android game that tasks players with solving puzzles by rotating tiles to make all “flows” match up with no loose ends. Each tile has a flow (e.g. road, path, grass, river) on each side, as well as a height (high, normal, low). There are a few hundred built-in levels, but players can also create, share, and import their own levels for extended playability.\n",
      "url"      : "/android-asynchronous-map-generator/",
      "date"     : "Jan 6, 2017",
      "content"  : "City Flow is an Android game that tasks players with solving puzzles by rotating tiles to make all “flows” match up with no loose ends. Each tile has a flow (e.g. road, path, grass, river) on each side, as well as a height (high, normal, low). There are a few hundred built-in levels, but players can also create, share, and import their own levels for extended playability.\n\nThe game features a level generator, where players can specify:\n\n\n  Puzzle width (2-15)\n  Puzzle height (2-15)\n  Environment (subset of tiles to use)\n  Whether a blank puzzle should be generated\n  Whether they wish to edit the puzzle before playing\n\n\nSince a puzzle can contain up to 225 tiles (15×15), each from a pool of 200+ different tile types, the amount of data to process can swiftly ramp up.\n\nAdditionally, since this process could take a long time, it must be performed off the main thread (asynchronously). The player also needs to be kept updated throughout the process with current progress, and have the ability to cancel midway through.\n\nThe Solution\n\nWe’re going to display an updating popup on screen, whilst the generation happens in the background using an AsyncTask . Generation will occur by cycling through every x and y position, generating a list of all possible tiles, then randomly selecting one. If a “dead end” is reached (e.g. a non-existent tile configuration is requested), limited backtracking will occur.\n\nUpdating Dialog\n\nFirst of all, a “currently generating” popup is displayed on screen, which calls the Puzzle Generator and handles displaying progress.\n\nNote the “execute” method called immediately after creation, this is what actually triggers the AsyncTask to start.\n\nprivate static void puzzleLoadingProgress(final Activity activity, int xValue, int yValue, int environmentId, boolean blankPuzzle, boolean shuffleAndPlay) {\n    final Dialog dialog = new Dialog(activity);\n    dialog.setContentView(R.layout.custom_dialog_puzzle_loading);\n    dialog.setCancelable(true);\n    ((TextView) dialog.findViewById(R.id.title)).setText(Text.get(\"WORD_LOADING\"));\n    dialog.show();\n\n    PuzzleGenerator puzzleGenerator = new PuzzleGenerator(activity,\n            dialog,\n            xValue,\n            yValue,\n            environmentId,\n            blankPuzzle,\n            shuffleAndPlay);\n    puzzleGenerator.execute(\"\");\n}\n\n\nThe required parameters are passed to the generator, namely:\n\n\n  Puzzle options (size, environment, whether to play immediately, etc)\n  UI elements that need to be kept updated on current progress (elements in the dialog)\n\n\nPuzzle Generator Constructor\n\nVariables are for the most part just assigned to local variables for future usage, except for UI elements which are found in the calling dialog.\n\nhasAllTiles() is a flag for whether the user has purchased the ability to access all tiles without unlocking them through gameplay, and is not relevant for this example.\n\npublic class PuzzleGenerator extends AsyncTask {\n    ... variables snipped ...\n\n    public PuzzleGenerator(Activity activity, Dialog dialog, int xValue, int yValue, int environmentId, boolean blankPuzzle, boolean shuffleAndPlay) {\n        this.activity = activity;\n        this.dialog = dialog;\n        this.xValue = xValue;\n        this.yValue = yValue;\n        this.environmentId = environmentId;\n        this.blankPuzzle = blankPuzzle;\n        this.shuffleAndPlay = shuffleAndPlay;\n        this.hasAllTiles = Iap.hasAllTiles();\n\n        this.progressText = (TextView) dialog.findViewById(R.id.progressText);\n        this.progressPercentage = (TextView) dialog.findViewById(R.id.progressPercentage);\n    }\n\n\nCancellability\n\nTo add the ability to cancel puzzle generation despite happening asynchronously, a simple cancel listener was added to the calling dialog before execution. This means that when the back button is pressed, the cancelReceived flag will be set to true, which the actual generators check during execution.\n\n@Override\nprotected void onPreExecute() {\n    dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {\n        @Override\n        public void onCancel(DialogInterface dialogInterface) {\n            cancel();\n        }\n    });\n}\n\npublic void cancel() {\n    cancelReceived = true;\n}\n\n\nBeginning Generation\n\nAfter onPreExecute has run, the main meat of the task doInBackground is called. This checks whether full puzzle generation needs to happen. If a blank puzzle is requested, then all tiles are selected as a predetermined “empty” tile for the selected environment, with no flow &amp; a normal height on all sides.\n\nThis article will only cover createFilledPuzzle(), since createEmptyPuzzle() is just a simpler version.\n\n@Override\n    protected Integer doInBackground(String... params) {\n    totalTiles = xValue * yValue;\n    if (blankPuzzle) {\n        return createEmptyPuzzle(xValue, yValue, environmentId);\n    } else {\n        return createFilledPuzzle(xValue, yValue, environmentId);\n    }\n}\n\n\nNotice the totalTiles local variable being set, this is used to calculate a % complete to display to the end user. After each tile is generated, onProgressUpdate is passed the total number of tiles generated. Using this it calculates how far through the process the generator is, and keeps the user updated in real time via the views on the calling dialog.\n\n@Override\nprotected void onProgressUpdate(Integer... values) {\n    int percent = (int) (((double) values[0]) / ((double) totalTiles) * 100);\n    progressPercentage.setText(String.format(Locale.ENGLISH, \"%1$d%%\", percent));\n    progressText.setText(String.format(Locale.ENGLISH, \"(%1$d/%2$d)\", values[0], totalTiles));\n}\n\n\nCreating The Puzzle\n\nFirst, placeholder puzzle objects are created. This gives a puzzle ID, so that the tiles can be saved to the correct puzzle. PuzzleCustom is also used as this is a player created puzzle, not one included in the game.\n\nprivate int createFilledPuzzle(int maxX, int maxY, int environmentId) {\n    int newPuzzleId = getNextCustomPuzzleId();\n    Puzzle newPuzzle = createBasicPuzzleObject(newPuzzleId);\n    PuzzleCustom puzzleCustom = createBasicPuzzleCustomObject(newPuzzleId, maxX, maxY);\n\n    newPuzzle.save();\n    puzzleCustom.save();\n\n\nWhilst the process can initially seem complex, essentially we’re just looping through every y position for every x position, from 0 to the maximum. Note the cancelReceived check, which will cancel puzzle generation if the back button has been pressed.\n\ngetPossibleTiles() is explained fully in the next step, it essentially returns a list of all tiles (and their rotation) that could fit into the specified x and y, based on the existing tiles. If any tiles are returned, one of them is randomly picked using a simple Math.random() function. Alternatively, the failed attempt counters are increased, and we move on to the next code block…\n\nList tiles = new ArrayList();\nint prevY = 0;\nint failedAttempts = 0;\nint totalAttempts = 0;\nint maxAttemptsPerTile = 3;\nint maxTotalAttempts = 10;\nfor (int x = 0; x &lt; maxX; x++) {\n    for (int y = 0; y &lt; maxY; y++) {\n        if (cancelReceived) {\n            newPuzzle.safelyDelete();\n            return 0;\n        }\n\n        List potentialTiles = getPossibleTiles(newPuzzleId, tiles, x, y, maxX - 1, maxY - 1, environmentId);\n        if (potentialTiles.size() &gt; 0) {\n            Tile selectedTile = potentialTiles.get(RandomHelper.getNumber(0, potentialTiles.size() - 1));\n            tiles.add(selectedTile);\n            prevY = y;\n            failedAttempts = 0;\n        } else {\n            failedAttempts++;\n            totalAttempts++;\n            failedTiles++;\n\n\nFirst, we check if the current tile has been tried too many times, or we’ve failed too many times during the puzzle in general. If so, we just give up, and put in an empty tile, otherwise we’ll end up backtracking forever! This happens more often the more complex the flow / height setup of the puzzle is.\n\nIf we want to try again, we remove the last tile in the generated tiles list, and get the previous tile’s x and y, so that the next generation iteration can try it again.\n\nWhilst being able to do multiple backtracks is essential, it’s important to set some kind of global maximum, otherwise a puzzle can get stuck, and it’s very hard to detect this situation (since tiles are generating successfully, but creating an impossible situation for the next tile).\n\nNote the publishProgress method being called after each iteration, as mentioned earlier.\n\n            if (failedAttempts &gt; maxAttemptsPerTile || totalAttempts &gt; maxTotalAttempts) {\n                tiles.add(new Tile(newPuzzleId, 0, x, y, Constants.ROTATION_NORTH));\n                prevY = y;\n                failedAttempts = 0;\n                totalAttempts = 0;\n                failedTiles++;\n            } else {\n                tiles.remove(tiles.size() - 1);\n                if (y == 0) {\n                    x--;\n                    y = maxY - 1;\n                } else {\n                    y = prevY - 1;\n                }\n            }\n        }\n        publishProgress(tiles.size());\n    }\n}\n\n\nThe puzzle is now generated, so we shuffle it if the user wants to play it immediately, otherwise save all the tiles, and return the new puzzle’s ID, so that we can redirect the player to either play or edit the level.\n\n\n    if (shuffleAndPlay) {\n        Puzzle.shuffle(tiles);\n        Tile.executeQuery(\"UPDATE tile SET default_rotation = rotation WHERE puzzle_id = \" + newPuzzleId);\n    } else {\n        Tile.saveInTx(tiles);\n    }\n    return newPuzzleId;\n}\n\n\nGet All Possible Tiles For Position\n\nTo identify possible tiles, we need to know the existing tiles (since we usually need to match their flow &amp; height), as well as what position we’re looking for.\n\nFirst we get the south &amp; west tiles. If we’re on the furthest south / west position (X / Y = 0), then there won’t be a tile in that position. These 2 tiles are required to calculate what flows we need. We get the tile type to avoid looking it up repeatedly.\n\nNext we calculate what flows are allowed on all sides. If we’re at the max X / Y, we’re at the edge, so no flows are allowed on that side. Otherwise, we look at the previously fetched tile types (using our knowledge of the tile’s current rotation) to identify what flows are allowed. Height is a very similar process, except that any height can touch the edge of the puzzle.\n\nThen we call the getPossibleTilesByRotation function 4 times, once assuming all potential tiles are facing North, then East, South, and West. This ensures that tiles that are suitable in multiple rotations are included repeatedly.\n\nprivate List getPossibleTiles(int puzzleId, List existingTiles, int tileX, int tileY, int maxX, int maxY, int environmentId) {\n    Tile southTile = tileY == 0 ? new Tile() : existingTiles.get(existingTiles.size() - 1); // Get the south tile, or an empty one if we're starting a new column\n    Tile westTile = tileX == 0 ? new Tile() : existingTiles.get(existingTiles.size() - (maxY + 1)); // Get the west tile (#Y tiles previous), or empty if new row\n\n    TileType southTileType = TileType.get(southTile.getTileTypeId());\n    TileType westTileType = TileType.get(westTile.getTileTypeId());\n\n    int nFlow = tileY == maxY ? 0 : Constants.FLOW_ANY;\n    int eFlow = tileX == maxX ? 0 : Constants.FLOW_ANY;\n    int sFlow = southTileType.getFlow(Constants.SIDE_NORTH, southTile.getRotation());\n    int wFlow = westTileType.getFlow(Constants.SIDE_EAST, westTile.getRotation());\n\n    // If there's no flow, then do any height we want\n    int nHeight = Constants.FLOW_ANY;\n    int eHeight = Constants.FLOW_ANY;\n    int sHeight = sFlow &gt; 0 &amp;&amp; tileY &gt; 0 ? southTileType.getHeight(Constants.SIDE_NORTH, southTile.getRotation()) : Constants.FLOW_ANY;\n    int wHeight = wFlow &gt; 0 &amp;&amp; tileX &gt; 0 ? westTileType.getHeight(Constants.SIDE_EAST, westTile.getRotation()) : Constants.FLOW_ANY;\n\n    // Make list\n    List tiles = getPossibleTilesByRotation(puzzleId, tileX, tileY, environmentId, Constants.ROTATION_NORTH, nFlow, eFlow, sFlow, wFlow, nHeight, eHeight, sHeight, wHeight);\n    tiles.addAll(getPossibleTilesByRotation(puzzleId, tileX, tileY, environmentId, Constants.ROTATION_WEST, wFlow, nFlow, eFlow, sFlow, wHeight, nHeight, eHeight, sHeight));\n    tiles.addAll(getPossibleTilesByRotation(puzzleId, tileX, tileY, environmentId, Constants.ROTATION_SOUTH, sFlow, wFlow, nFlow, eFlow, sHeight, wHeight, nHeight, eHeight));\n    tiles.addAll(getPossibleTilesByRotation(puzzleId, tileX, tileY, environmentId, Constants.ROTATION_EAST, eFlow, sFlow, wFlow, nFlow, eHeight, sHeight, wHeight, nHeight));\n\n    return tiles;\n}\n\n\nGet Possible Tiles For Current Rotation\n\nSince we’re using a database to store all our tile information, we manually construct a query to get all possible tiles based on the parameters received.\n\nThe match function is used extensively, it is used so that -1 can be used to represent “Any”. For example, a value of 1 would result in name = 1, whilst -1 would result in name &gt;= -1.\n\nFirst, we construct the SQL for checking the flow. This is relatively straightforward, the only complexity is forcing the very first tile to have a flow (otherwise we might get a puzzle of all decorative / empty tiles!). We then repeat the process for height.\n\nNext, we make sure we’re only selecting from tiles that are unlocked (unless they have unlocked accessing all tiles) in the selected environment. The final list of tile types are then made into tile objects for the puzzle, most importantly with the selected rotation.\n\nprivate List getPossibleTilesByRotation(int puzzleId, int x, int y, int environmentId, int rotation, int nFlow, int eFlow, int sFlow, int wFlow, int nHeight, int eHeight, int sHeight, int wHeight) {\n    String flowSql = String.format(Locale.ENGLISH, \"%1$s AND %2$s AND %3$s AND %4$s\",\n            match(\"flow_north\", nFlow),\n            match(\"flow_east\", eFlow),\n            match(\"flow_south\", sFlow),\n            match(\"flow_west\", wFlow));\n    String forceFlowSql = (x == 0 &amp;&amp; y == 0 ? \" AND (flow_north &gt; 0 OR flow_east &gt; 0 OR flow_south &gt; 0 OR flow_west &gt; 0)\" : \"\");\n\n    String heightSql = String.format(Locale.ENGLISH, \"%1$s AND %2$s AND %3$s AND %4$s\",\n            match(\"height_north\", nHeight),\n            match(\"height_east\", eHeight),\n            match(\"height_south\", sHeight),\n            match(\"height_west\", wHeight));\n\n    String sql = String.format(Locale.ENGLISH, \"environment_id %1$s %2$d AND \" + flowSql + forceFlowSql + \" AND \" + heightSql + \" AND status %3$s %4$d\",\n            environmentId &gt; 0 ? \"=\" : \"&gt;=\", environmentId,\n            hasAllTiles ? \"&gt;=\" : \"=\",\n            Constants.TILE_STATUS_UNLOCKED);\n    List tileTypes = TileType.find(TileType.class, sql);\n\n    List tiles = new ArrayList();\n    for (TileType tile : tileTypes) {\n        tiles.add(new Tile(puzzleId, tile.getTypeId(), x, y, rotation));\n    }\n    return tiles;\n}\n\nprivate static String match(String name, int value) {\n    return String.format(Locale.ENGLISH, \"(%1$s %2$s %3$s)\",\n            name,\n            (value &gt;= 0 ? \"=\" : \"&gt;=\"),\n            value);\n}\n\n\nThe Conclusion\n\nThe puzzle generator is very much an optional feature of City Flow, but one which has grown more and more powerful over time. It has gone through various refactorings to improve readability, but unfortunately the more complex parts are still rather hard to understand. However, it performs excellently, and should hopefully provide increased longevity to the game’s lifespan by allowing more levels to be generated than players can ever complete.\n\nWhilst there are quite a few domain specific elements in the code (e.g. hasAllTiles, environmentId), the general idea of generating a data structure in the background and keeping users updated is definitely applicable to other scenarios.\n\nTo improve performance, reducing the number of String.formats would be a good start, as there are currently 44 per tile, resulting in a worst case scenario of almost 10k calls ((44 * (15 * 15)) = 9900).\n\nThe full PuzzleGenerator.java file can be downloaded from GitHub Gist.\n\nDisclaimer: I wrote City Flow, I’m featuring it here because I know the codebase very well!\n"
    } 
  
]