Quick snippets of Android-related code and bookmarks to increase productivity.

Map

There are two ways to implement Google Maps into an Android app: MapFragment and MapView

Setup:

More resources:

  • GoogleMap API Reference: https://developers.google.com/android/reference/com/google/android/gms/maps/GoogleMap

How to show map marker at street address

import android.location.Geocoder
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions

...

val markerName = "Example"
val streetAddress = "123 Fake St; Denver, CO 80246"
if (Geocoder.isPresent()) {
    val geocoder = Geocoder(requireContext())
    val addresses = geocoder.getFromLocationName(streetAddress, 1)
    val address = if (addresses == null) null else addresses[0]
    if (address != null) {
        val location = LatLng(address.latitude, address.longitude)
        map?.addMarker(MarkerOptions().position(location).title(markerName))
    }
} else {
    toast("Geocoder is not available on your device")
}

View

Default sample page

Syntax Highlighting with Pygments

{% highlight language="java" %}
    public abstract class OrchidGenerator extends Prioritized implements OptionsHolder {
        
        protected final String key;
    
        protected final OrchidContext context;
    
        @Inject
        public OrchidGenerator(OrchidContext context, String key, int priority) {
            super(priority);
            this.key = key;
            this.context = context;
        }
    
        /**
         * A callback to build the index of content this OrchidGenerator intends to create.
         *
         * @return a list of pages that will be built by this generator
         */
        public abstract List<? extends OrchidPage> startIndexing();
    
        /**
         * A callback to begin generating content. The index is fully built and should not be changed at this time. The
         * list of pages returned by `startIndexing` is passed back in as an argument to the method.
         *
         * @param pages the pages to render
         */
        public abstract void startGeneration(Stream<? extends OrchidPage> pages);
    }
{% endhighlight %}

 1 public abstract class OrchidGenerator extends Prioritized implements OptionsHolder {
 2         
 3         protected final String key;
 4     
 5         protected final OrchidContext context;
 6     
 7         @Inject
 8         public OrchidGenerator(OrchidContext context, String key, int priority) {
 9             super(priority);
10             this.key = key;
11             this.context = context;
12         }
13     
14         /**
15          * A callback to build the index of content this OrchidGenerator intends to create.
16          *
17          * @return a list of pages that will be built by this generator
18          */
19         public abstract List<? extends OrchidPage> startIndexing();
20     
21         /**
22          * A callback to begin generating content. The index is fully built and should not be changed at this time. The
23          * list of pages returned by `startIndexing` is passed back in as an argument to the method.
24          *
25          * @param pages the pages to render
26          */
27         public abstract void startGeneration(Stream<? extends OrchidPage> pages);
28     }


Embed Github Gist

{% gist user="cjbrooks12" id="83a11f066388c9fe905ee1bab47ecca8" %}

# Create specified number of articles for Hugo benchmarks
from datetime import datetime
import random
import string
from sys import argv
import os
def generateWord(min_length = 1, max_length = 10):
length = random.randint(min_length, max_length)
word = ''.join(random.choice(string.letters) for _ in range(length))
return word
def generateSentence(words):
return ' '.join([generateWord() for i in range(words)])
def getRandomDate():
year = random.choice(range(startYear, endYear))
month = random.choice(range(1, 13))
day = random.choice(range(1, 29))
hours = random.choice(range(0, 24))
minutes = random.choice(range(0, 60))
seconds = random.choice(range(0, 60))
return datetime(year, month, day, hours, minutes, seconds).strftime("%Y-%m-%d_%H-%M-%S")
def generateTagList():
return '["' + '","'.join([random.choice(tags) for i in range(numTagsPerPost)]) + '"]'
def createPost(outputDir):
title = generateSentence(8)
desc = generateSentence(20)
tagsList = generateTagList()
year = random.choice(range(startYear, endYear))
month = random.choice(range(1, 13))
day = random.choice(range(1, 29))
slug = str(year).rjust(2, '0') + '-' + str(month).rjust(2, '0') + '-' + str(day).rjust(2, '0') + '-' + title.replace(' ', '-').lower()
slug = ''.join(c for c in slug if c.isalnum() or c == '-')
with open('%s/%s.md' % (outputDir, slug), 'w') as f:
f.write('+++\n')
f.write('title = "%s"\n' % title)
f.write('description = "%s"\n' % desc)
f.write('tags = %s\n' % tagsList)
# Use UTC time to avoid having to mess with timezones and daylight saving time
f.write('date = "%s"\n' % datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S-00:00"))
f.write('slug = "%s"\n' % slug)
f.write('+++\n\n')
# Generate blocks of random words
num_paragraphs = random.randint(5, 10)
for i in range(num_paragraphs):
f.write(generateSentence(random.randint(50, 100)))
f.write('\n\n')
dir_path = os.path.dirname(os.path.realpath(__file__))
# Set defaults
outputDir = dir_path + '/posts'
numPosts = 500
numTags = 30
numTagsPerPost = 5
startYear = 1950
endYear = 2020
# Generate random categories
tags = [generateWord(6, 14) for i in range(numTags)]
# ensure directory exists
if not os.path.exists(outputDir):
os.makedirs(outputDir)
for i in range(numPosts):
createPost(outputDir)