[PYTHON] Qiita Syntax Highlighting Memorandum

Syntax Highlighting: List of Supported Languages at Qiita --Qiita Wright's memorandum.

Probably Qiita's syntax highlighting engine is Pygments.

The usage and examples of each item are shown.

shell related

console For terminal output.

console


$ apt-cache depends auditd
auditd
Dependence: lsb-base
 |Dependence: mawk
Dependence: gawk
Dependence: init-system-helpers
Dependence: libaudit1
Dependence: libauparse0
Dependence: libc6
Dependence: libgssapi-krb5-2
Dependence: libkrb5-3
Dependence: libwrap0
Suggestion: audispd-plugins
$

bash An example of spamhaus.sh from cowgill / spamhaus.

spamhaus.sh


#!/bin/bash

# based off the following two scripts
# http://www.theunsupported.com/2012/07/block-malicious-ip-addresses/
# http://www.cyberciti.biz/tips/block-spamming-scanning-with-iptables.html

# path to iptables
IPTABLES="/sbin/iptables";

# list of known spammers
URL="www.spamhaus.org/drop/drop.lasso";

# save local copy here
FILE="/tmp/drop.lasso";

# iptables custom chain
CHAIN="Spamhaus";

# check to see if the chain already exists
$IPTABLES -L $CHAIN -n

# check to see if the chain already exists
if [ $? -eq 0 ]; then

    # flush the old rules
    $IPTABLES -F $CHAIN

    echo "Flushed old rules. Applying updated Spamhaus list...."    

else

    # create a new chain set
    $IPTABLES -N $CHAIN

    # tie chain to input rules so it runs
    $IPTABLES -A INPUT -j $CHAIN

    # don't allow this traffic through
    $IPTABLES -A FORWARD -j $CHAIN

    echo "Chain not detected. Creating new chain and adding Spamhaus list...."

fi;

# get a copy of the spam list
wget -qc $URL -O $FILE

# iterate through all known spamming hosts
for IP in $( cat $FILE | egrep -v '^;' | awk '{ print $1}' ); do

    # add the ip address log rule to the chain
    $IPTABLES -A $CHAIN -p 0 -s $IP -j LOG --log-prefix "[SPAMHAUS BLOCK]" -m limit --limit 3/min --limit-burst 10

    # add the ip address to the chain
    $IPTABLES -A $CHAIN -p 0 -s $IP -j DROP

    echo $IP

done

echo "Done!"

# remove the spam list
unlink $FILE

Python related

python, py, python3, py3

This is the python source as it is. The display is slightly different between python and python3.

python / python3 example

python


import re
import sys
import json
import six
from voluptuous import Schema, Required, Any, Range, Invalid, ALLOW_EXTRA


def validate_io_size(v):
	if re.search("^[0-9]+[bkm]", v) is None:
		raise Invalid("not a valid value (%s)" % str(v))


def get_schema():
	schema = Schema({
		"comment"					: six.text_type,
		Required("operation")		: Any("read", "write"),
		"thread"					: Range(min=1),
		Required("io_size")			: validate_io_size,
		Required("access_percentage")	: Range(min=1, max=100),
	}, extra=ALLOW_EXTRA)
	
	return schema


def main():
	schema	= get_schema()
	
	with open(sys.argv[1], "r") as fp:
		dict_sample	= json.load(fp)
	
	schema(dict_sample)
	six.print_(dict_sample)
	
	return 0


if __name__ == '__main__':
	sys.exit(main())

python3


import re
import sys
import json
import six
from voluptuous import Schema, Required, Any, Range, Invalid, ALLOW_EXTRA


def validate_io_size(v):
	if re.search("^[0-9]+[bkm]", v) is None:
		raise Invalid("not a valid value (%s)" % str(v))


def get_schema():
	schema = Schema({
		"comment"					: six.text_type,
		Required("operation")		: Any("read", "write"),
		"thread"					: Range(min=1),
		Required("io_size")			: validate_io_size,
		Required("access_percentage")	: Range(min=1, max=100),
	}, extra=ALLOW_EXTRA)
	
	return schema


def main():
	schema	= get_schema()
	
	with open(sys.argv[1], "r") as fp:
		dict_sample	= json.load(fp)
	
	schema(dict_sample)
	six.print_(dict_sample)
	
	return 0


if __name__ == '__main__':
	sys.exit(main())

pycon

Probably for console output when python is started on the console like ↓.

# python
Python 2.5.2 (r252:60911, Jan 24 2010, 14:53:14)
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

pycon example

From http://docs.python.jp/2/library/random.html An example of python console output modified with pycon.

pycon


>>> random.random()        # Random float x, 0.0 <= x < 1.0
0.37444887175646646
>>> random.uniform(1, 10)  # Random float x, 1.0 <= x < 10.0
1.1800146073117523
>>> random.randint(1, 10)  # Integer from 1 to 10, endpoints included
7
>>> random.randrange(0, 101, 2)  # Even integer from 0 to 100
26
>>> random.choice('abcdefghij')  # Choose a random element
'c'

>>> items = [1, 2, 3, 4, 5, 6, 7]
>>> random.shuffle(items)
>>> items
[7, 3, 2, 5, 6, 4, 1]

>>> random.sample([1, 2, 3, 4, 5],  3)  # Choose 3 elements
[4, 1, 5]

pytb/py3tb

For stack trace output by python.

pytb / py3tb example

In the example below, no difference between pytb and py3tb was visible.

pytb


Traceback (most recent call last):
  File "<doctest...>", line 10, in <module>
    lumberjack()
  File "<doctest...>", line 4, in lumberjack
    bright_side_of_death()
IndexError: tuple index out of range

py3tb


Traceback (most recent call last):
  File "<doctest...>", line 10, in <module>
    lumberjack()
  File "<doctest...>", line 4, in lumberjack
    bright_side_of_death()
IndexError: tuple index out of range

SQL related

sql For SQL queries.

sql


SELECT hoge FROM table_namme WHERE value > 0

sqlite3

sqlite3


$ sqlite3
SQLite version 3.8.7.1 2014-10-29 13:59:56
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> create table hoge(key text, value integer);
sqlite> insert into hoge values("a", 1);
sqlite> insert into hoge values("b", 2);
sqlite> insert into hoge values("c", 3);
sqlite>
sqlite> select key, value from hoge;
a|1
b|2
c|3
sqlite>

HTML related

HTML

html


<html>
	<head>
		<title>Hello world</title>
	</head>
	<body>
		Hello world
	</body>
</html>

CSS For cascading style sheets.

css


h1, h2, h3, h4 { margin-top: 0.5em; margin-bottom: 0.1em; }

h3 { margin-left: 0.5em; }
h4 { margin-left: 1.5em; }

body { counter-reset: part; }
h2 { counter-reset: chapter; }
h2:before {
	content: counter(part) ". ";
	counter-increment: part;
}

h3 { counter-reset: section; }
h3:before {
	content: counter(part) "." counter(chapter) ". ";
	counter-increment: chapter;
}

h4 { counter-reset: subsection; }
h4:before {
	content: counter(part) "." counter(chapter) "." counter(section) ". ";
	counter-increment: section;
}

Linux command output

diff

--- lhs 2016-01-05 08:13:48.341912876 +0900
+++ rhs 2016-01-05 08:14:19.913913237 +0900
@@ -1,4 +1,4 @@
 hoge
-foo
+aaaaaaaaaaaaa
 bar
-
+bbbbbbbbbbbbbbb

Other

JSON Although not on the list, syntax highlighting is also valid for JSON.

JSON


{
	"text"		: "value",
	"value"		: 100,
	"list"		: ["a", "b", "c"],
	"nest_dict"	: {
		"child"	: 1
	}
}

YAML From [Demo] of pygments (http://pygments.org/demo/97004/)

yaml


time: 120
title: '테스트 컨테스트'
contestpw: '0000'

languages:
  -
    display: 'GNU C 4.6.2'
    compile: 'gcc -lm -O2 -o {:basename}.exe {:mainfile}'
    execute: '{:basename}.exe'
    binary: '{:basename}.exe'
  -
    display: 'GNU C++ 4.6.2'
    compile: 'g++ -O2 -o {:basename}.exe {:mainfile}'
    execute: '{:basename}.exe'
    binary: '{:basename}.exe'
  -
    display: 'Microsoft Visual C++ 2010'
    compile: 'cl /Ox {:mainfile}'
    execute: '{:mainfile}.exe'
    binary: '{:mainfile}.exe'
  -
    display: 'Oracle Java SE 7'
    compile: 'javac {:mainfile}'
    execute: 'java {:basename}'
    binary: '{:basename}.class'

problems:
  -
    title: 'HELLOWORLD'
    input: './problems/HELLOWORLD/helloworld.in'
    output: './problems/HELLOWORLD/helloworld.out'
    timelimit: 10
    external_validation: yes
    validator: './validators/Validator.jar'
    validationcmd: 'java -jar {:validator} {:infile} {:outfile} {:ansfile} {:resfile} rz'
    color: 'color0'
  -
    title: 'HELLOWORLD2'
    input: './problems/HELLOWORLD/helloworld.in'
    output: './problems/HELLOWORLD/helloworld.out'
    timelimit: 1
    external_validation: no
    validator: 1
    validator_ignorecase: yes
    color: 'color1'

judgements:
  - 'Yes'
  - 'No - Compilation Error'
  - 'No - Run-time Error'
  - 'No - Time-limit Exceeded'
  - 'No - Wrong Answer'
  - 'No - Excessive Output'
  - 'No - Output Format Error'
  - 'No - Other - Contact Staff'

groups:
  - { name: 'KAIST', scoreboard: yes }
  - { name: 'Test accounts', scoreboard: no }

accounts:
  admins: # default scoreboard: no
    # default administrator -> 1
    - { name: 'Administrator 2', password: '0000' }

  judges: # default scoreboard: no
    - { name: 'Judge 1', password: 'judge1' }
    - { name: 'Judge 2', password: 'judge2' }

  scoreboards: # default scoreboard: no
    - { name: 'Scoreboard 1', password: 'scoreboard1' }
    - { name: 'Scoreboard 2', password: 'scoreboard2' }

  teams: # default scoreboard: yes
    - { name: 'Team 1', group: 1, password: 'team1' }
    - { name: 'Team 2', group: 2, password: 'team2' }
    - { name: 'Team 3', password: 'team3' }
    - { name: 'Team 4', scoreboard: no, password: 'team4' }

The benefits are not so visible in the ansible playbook format.

yaml


---
- name: reboot OS
  hosts: server-under-test
  gather_facts: no
  tasks:
    - name: reboot
      shell: reboot
      async: 0
      poll: 0 

    - name: wait for SSH port down
      local_action: wait_for host={{ inventory_hostname }} port=22 state=stopped

    - name: wait for SSH port up
      local_action: wait_for host={{ inventory_hostname }} port=22 state=started delay=10

    - pause: seconds=5

Recommended Posts

Qiita Syntax Highlighting Memorandum
Frequently used syntax memorandum for each language
Syntax highlighting source code in PowerPoint / Keynote