Code Breaker
Switching back and forth between programming languages sometimes causes me to break my own code. This cheat sheet will hopefully help prevent that.
| Kind | Javascript | Jekyll Liquid | Python | Ruby | 
|---|---|---|---|---|
| Comment | /* hello there */ // also hi | {% comment %} hello there {% endcomment %} | # hello there | # hello there | 
| Lowercase | 'ABC'.toLowerCase() | {{ 'ABC' | downcase }} | 'ABC'.lower() | 'ABC'.downcase | 
| Uppercase | 'abc'.toUpperCase() | {{ 'abc' | upcase }} | 'abc'.upper() | 'abc'.upcase | 
| String | String(2001) 2001 + '' 2001.toString() | {{ 2001 | downcase }} | str(2001) | 2001.to_s | 
| Integer | Number('2001') '2001' * 1 parseInt('2001',10) | {{ '2001' | plus: 0 }} {{ '2001' | times: 1 }} | int('2001') | '2001'.to_i | 
| Array | ['a','b','c'] | {{ 'a,b,c' | split: ',' }} | ['a','b','c'] | ['a','b','c'] | 
| Push | x = ['a','b','c'] x.push('d') | {% assign x = 'a,b,c' | split: ',' %} {% assign y = 'd' | split: ',' %} {% assign xy = x | concat: y %} | x = ['a','b','c'] x.append('d') | x = ['a','b','c'] x.push('d') | 
| Length | 'abc'.length ['a','b','c'].length | {{ 'abc' | size }} {{ 'a,b,c' | split:',' | size }} | len('abc') len(['a','b','c']) | 'abc'.length ['a','b','c'].length | 
| Substring | 'abcdef'.includes('cd') | {{ 'abcdef' contains 'cd' }} | 'cd' in 'abcdef' | 'abcdef'.include? 'cd' | 
| Conditional | if (_____) { ... } else if (_____) { ... } else { ... } | {% if _____ %} ... {% elsif _____ %} ... {% else %} ... {% endif %} | if _____: ... elif _____: ... else: ... | if _____ ... elsif _____ ... else ... end | 
Python
Run Python shell
# Alphabetize array
jumbled.sort()
# Copy files
shutil.copy('/path/of/*.txt', '/path/of/dest/')
# Check for attribute
if slug in yyyy and 'imdb' in yyyy[slug]:
	imdb = yyyy[slug]['imdb']
# Check for starts with
if bible.startswith('In the beginning'):
	print(bible)
# Concat strings 1
var1 = "foo"
var2 = "bar"
var3 = var1 + var2
# Concat strings 2
"%s:%d" % (str1, num2)
# Convert array to string
', '.join(['a','b','c'])
# Date formats borrowed from strftime.org
%a  Mon        Weekday as locale’s abbreviated name.
%A  Monday     Weekday as locale’s full name.
%d  30         Day of the month as a zero-padded decimal number.
%-d 30         Day of the month as a decimal number.
%b  Sep        Month as locale’s abbreviated name.
%B  September  Month as locale’s full name.
%m  09         Month as a zero-padded decimal number.
%-m 9          Month as a decimal number. (Platform specific)
%y  13         Year without century as a zero-padded decimal number.
%Y  2013       Year with century as a decimal number.
# Filter out non-alpha-numeric characters
import re
regex = re.compile('[^a-zA-Z0-9]')
regex.sub('', 'a.b!c@d#e$f%g')
# Find type of variable
type('abc')
type('abc') is str
type(0)
type(0) is int
type(['a','b','c'])
type(['a','b','c']) is list
type({'a','b','c'})
type({'a','b','c'}) is dict
# Get files in a directory
files = os.listdir('../_data/')
for file in files:
	print(file)
# Get file size
mysize = os.stat('/path/of/file.txt').st_size
# Limit a loop
for count, item in enumerate(items, start=1):
	print(count, item)
# Read/Write date
when = str(my_date)
dayy = datetime.strptime(when, '%Y-%m-%d')
print(dayy.strftime('%A, %B %d, %Y'))
# Read from simple file into a variable
with open('data.txt', 'r') as myfile:
	data = myfile.read()
# Read from YAML file (like Jekyll front matter)
import yaml
with open('../path/whatever.yml', 'r') as stream:
	try:
		yyyy = yaml.load(stream)
	except yaml.YAMLError as exc:
		print(exc)
# Reference script name
import os
print(os.path.basename(__file__))
# Replace string
'Hello world'.replace('world', 'sailor')
# Remove parenthetical text in a string
mystr = 'Wonder Woman (Diana) and Superman (Clark)'
mystr = re.sub(r' \(.+?\)', '', mystr)
# Replace last occurance of substring
def rreplace(s, old, new, occurrence):
	li = s.rsplit(old, occurrence)
	return new.join(li)
rreplace('abcdcdcd', 'c', 'C', 1)
# Split a URL
'//www.website.com/page/99/'.split('/')[4]
# Stop
import sys
sys.exit("Error message")
# Truncate a string (abc)
mystr = 'abcdef'
print(mystr[:3])
# Truncate a string at the beginning (def)
mystr = 'abcdef'
print(mystr[3:])
# Try/Catch Exceptions
try:
	mynum = 1/0
except ZeroDivisionError:
	print('No dividing by zero!')
	raise
# Waiting ...
for i in range(10):
	sys.stdout.write('.')
print
# Write to file
w_file = '../path/%s' % (filename)
with open(w_file, 'w') as f:
	f.write('---\n')
	f.write('title: "%s"\n' % (title))
	f.write('---\n')
	f.write('Blah blah blah.'))
	f.close()
# Python UnicodeEncodeError: 'ascii' codec can't encode character in position X: ordinal not in range(128)
myvar = myvar.encode('ascii', 'ignore')
# or
myvar = myvar.encode('utf-8')
Ruby
Run Ruby shell# Replace string mytext.gsub! 'this', 'that' # Write to console puts "Hello world"
Jekyll Liquid
{% comment %} Format date: Fri, Mar 11, 2016. {% endcomment %}
{{ article.published_at | date: '%a, %b %d, %Y' }}
{% comment %} Format date: November 5, 1955. {% endcomment %}
{{ article.published_at | date: '%B %d, %Y' }}
{% comment %} Loop on list {% endcomment %}
{% assign sytes = 'biog,imdb,rott,tcmm,wiki' | split: ',' %}
{% for syte in sytes %}
{% endfor %}
{% comment %} Show the first character in a string. // a {% endcomment %}
{{ "a-to-z" | slice: 0 }}
{% comment %} Show a range of characters in a string. // -to- {% endcomment %}
{{ "a-to-z" | slice: 1, 4 }}
{% comment %} Show the last character in a string. // f {% endcomment %}
{{ "a-to-z" | slice: -1 }}
{% comment %} Sorting {% endcomment %}
{{ page.tags | sort }}
{{ site.posts | sort: 'author' }}
{{ site.pages | sort: 'title', 'last' }}
{% comment %} Truncate {% endcomment %}
{{ page.desc | truncate: 10 }}
{{ page.desc | truncate: 10,'(more)' }}
{{ page.desc | truncate: 10,'' }}
Javascript
Run Javascript shell
// Try/catch
try {
	some.thing = 'stupid';
}
catch(err) {
	console.log('You did something stupid.');
}
Regular Expressions
regextester.com | regular-expressions.info
# Find Hulk, but not Hulk Hogan. \bHulk\b(?! Hogan) # Find lots of hyphens. -+ # Find HTML tags. <[^<]+?>
Other
Character References
unicodelookup.com | W3 Char Ref
Link Examples
		Do you have a question about any of this stuff? Ask me.