The singularity is here and it is not in the form of artificial general intelligence. It is in the form of franken-algorithms, algorithms that work with and against algorithms and learn independently of human input. It's very easy for these algorithms to create algorithms that humans can't understand because these algorithms optimize to reach toward certain goals by any means, including ones that don't follow conventional logic and ethical contexts.
Further reading: https://www.theguardian.com/technology/2018/aug/29/coding-algorithms-frankenalgos-program-danger
Monday, September 03, 2018
Tuesday, December 12, 2017
Copy working directory path to Mac clipboard
To copy the current working directory's path to the Mac's clipboard:
alias cppwd='eval "echo `pwd` | tr -d \\\\n | pbcopy"'Put this alias in .profile. To use, enter cppwd.
Tuesday, November 07, 2017
Fix init sequence in Raspberry Pi
If the init sequence gets broken and you can't get to a shell on a Raspberry Pi (I'm using 3 model B), you can boot into recovery mode this way.
- Hit shift when starting up.
- Hit "e" to edit config
- tab over to cmdline.txt
- add to the end of the line
init=/bin/sh - hit ok, then Esc to boot...... it will boot you in to a command line
# mount -n -o remount,rw /(this will remount / so you can make changes) - now you should be able to edit the init.d config.
- when you reboot again.... hold shift and remove the init=/bin/sh
Friday, November 03, 2017
Thursday, November 02, 2017
Friday, October 13, 2017
Verifying OpenSSL certificates
Verifying that a certificate is issued by a CA
How to use OpenSSL on the command line to verify that a certificate was issued by a specific CA, given that CA's certificate:
$ openssl verify -verbose -CAfile cacert.pem server.crt server.crt: OK
Verify that a private key matches a certificate
$ openssl x509 -noout -modulus -in server.crt | openssl md5 $ openssl rsa -noout -modulus -in server.key | openssl md5The resultant hashes should match.
Thursday, September 28, 2017
Chaining class decorators
The last (i.e. outer) decorator's behavior gets executed first.
def require_authentication_permission(permission): def decorator(cls): cls.dispatch = method_decorator( permission_required( permission, raise_exception=True) )(cls.dispatch) cls2 = class_login_required(cls) return cls2 return decoratorIn this case, the execution order is:
- class_login_required
- permission_required
Monday, September 25, 2017
Logging in Django
To log to console in Django. Source: Logging | djangoproject.com
settings.py
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
},
},
}
File that uses logging
import logging
logger = logging.getLogger('django')
Write to log
logger.info('Hello')
Tuesday, September 19, 2017
Disable highlighting links in Vim
By default, Vim underlines the text inside anchor tags, including spaces, e.g.:
Some textTo disable this, create ~/.vim/syntax/html.vim:
" disable the current htmlLink syntax
highlight link htmlLink text
Wednesday, September 13, 2017
Mapping Keys in Mac OS 10.12 Sierra
To map keys in Mac OS 10.12 Sierra, install Karabiner-Elements.
I have a UK keyboard but am used to the US layout, so I've changed the section symbol § for the grave symbol `.
Being a vim user, I also like having
I have a UK keyboard but am used to the US layout, so I've changed the section symbol § for the grave symbol `.
Being a vim user, I also like having
- the esc key next to the shift key
- the right command key act as a control key
Tuesday, September 12, 2017
Block domains on search engine results
Greasemonkey script to allow blocking of domains in search engine results. Works for Google, Duckduckgo and various other search engines.
Google Hit Hider by Domain (Search Filter / Block Sites)
Google Hit Hider by Domain (Search Filter / Block Sites)
Friday, September 08, 2017
Django Forms
Some common uses of Django Forms.
f = Form(request.POST)
Instantiating a form with data a dictionary, e.g. from POST, creates a form populated with the field-name & field-value pairs in the dictionary.
f.errors
Returns dictionary of errors with keys being field names.
f['field_name'].errors
Returns list of errors for the specified field.
bound_form = self.form_class(request.POST)
return render(request, self.template_name, {'form': bound_form})
In a class-based view, renders a form with data bound from POST. bound_form.is_bound returns True.
model_instance = get_object_or_404(
self.form_class.Meta.model, slug__iexact=slug)
bound_form = self.form_class(request.POST, instance=model_instance)
As with previous line, renders a form with data bound from POST but also associated with a model instance so that it can be modified with a subsequent:
model_instance = bound_form.save()
form_class(initial={'title': 'Something'})
Creates a form with a field filled in already. However, the form is not bound.
f = Form(request.POST)
Instantiating a form with data a dictionary, e.g. from POST, creates a form populated with the field-name & field-value pairs in the dictionary.
f.errors
Returns dictionary of errors with keys being field names.
f['field_name'].errors
Returns list of errors for the specified field.
bound_form = self.form_class(request.POST)
return render(request, self.template_name, {'form': bound_form})
In a class-based view, renders a form with data bound from POST. bound_form.is_bound returns True.
model_instance = get_object_or_404(
self.form_class.Meta.model, slug__iexact=slug)
bound_form = self.form_class(request.POST, instance=model_instance)
As with previous line, renders a form with data bound from POST but also associated with a model instance so that it can be modified with a subsequent:
model_instance = bound_form.save()
form_class(initial={'title': 'Something'})
Creates a form with a field filled in already. However, the form is not bound.
Monday, September 04, 2017
Hide vim swap files in vim browser
While browsing files with vim, e.g. by entering the command ":e .", you might see a lot of swap files (*.swp, *.sw?) if you're using buffers. To hide them:
:let g:netrw_list_hide= '.*\.sw\w$'
Sunday, September 03, 2017
Bash Colors
#!/bin/bash
#
# This file echoes a bunch of color codes to the
# terminal to demonstrate what's available. Each
# line is the color code of one forground color,
# out of 17 (default + 16 escapes), followed by a
# test use of that color on all nine background
# colors (default + 8 escapes).
#
T='gYw' # The test text
echo -e "\n 40m 41m 42m 43m\
44m 45m 46m 47m";
for FGs in ' m' ' 1m' ' 30m' '1;30m' ' 31m' '1;31m' ' 32m' \
'1;32m' ' 33m' '1;33m' ' 34m' '1;34m' ' 35m' '1;35m' \
' 36m' '1;36m' ' 37m' '1;37m';
do FG=${FGs// /}
echo -en " $FGs \033[$FG $T "
for BG in 40m 41m 42m 43m 44m 45m 46m 47m;
do echo -en "$EINS \033[$FG\033[$BG $T \033[0m";
done
echo;
done
echo
Source: http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html
Saturday, September 02, 2017
Disable mouse acceleration on Mac
Mouse acceleration makes it hard for me to point and click things based on muscle memory, so I turn it off by entering into the terminal:
Please let me know if you know a clean way to persist this setting.
defaults write .GlobalPreferences com.apple.mouse.scaling -1Optionally, you can make an alias in ~/.profile and just enter the alias when you need to re-disable it, which you'll have to do often as the Mac resets this when you adjust mouse speed and sometimes upon login:
alias ma="defaults read .GlobalPreferences com.apple.mouse.scaling; defaults write .GlobalPreferences com.apple.mouse.scaling -1"Note that the first command prints the current mouse acceleration, and the second one changes it.
Please let me know if you know a clean way to persist this setting.
Vim for Python
Option 1
~/.vimrcsyntax enable~/.vim/python
if !exists("autocommands_loaded")
let autocommands_loaded = 1
autocmd BufRead,BufNewFile,FileReadPost *.py source ~/.vim/python
endif
" This beauty remembers where you were the last time you edited the file, and returns to the same position.
au BufReadPost * if line("'\"") > 0|if line("'\"") <= line("$")|exe("norm '\"")|else|exe "norm $"|endif|endif
" The magical turn-Vim-into-a-Python-IDE vim resource file!Source: https://dev.launchpad.net/UltimateVimPythonSetup minus the pydoc.vim part, which breaks it on my machine.
"
" Mostly taken from http://www.sontek.net/category/Vim.aspx
" Other bits culled from various sources, Canonical guys, or made up by me.
"
" Julian Edwards 2008-05-30
" Wrapping and tabs.
set tw=78 ts=4 sw=4 sta et sts=4 ai
" More syntax highlighting.
let python_highlight_all = 1
" Smart indenting
set smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class
" Auto completion via ctrl-space (instead of the nasty ctrl-x ctrl-o)
set omnifunc=pythoncomplete#Complete
inoremap
" Wrap at 72 chars for comments.
set formatoptions=cq textwidth=72 foldignore= wildignore+=*.py[co]
" Highlight end of line whitespace.
highlight WhitespaceEOL ctermbg=red guibg=red
match WhitespaceEOL /\s\+$/
" The next two highlight matches break the previous one, I don't know why.
" Show long lines.
"highlight LongLine guibg=red ctermbg=red
"match LongLine /\%>79v.\+/
" Highlight bzr merge markers.
"highlight MergeMarker guibg=red ctermbg=red
"match MergeMarker /^[<=>\|]\{7\}\( [A-Z]\+\)?$/
" `gf` jumps to the filename under the cursor. Point at an import statement
" and jump to it!
python << EOF
import os
import sys
import vim
for p in sys.path:
if os.path.isdir(p):
vim.command(r"set path+=%s" % (p.replace(" ", r"\ ")))
EOF
" Use :make to see syntax errors. (:cn and :cp to move around, :dist to see
" all errors)
set makeprg=python\ -c\ \"import\ py_compile,sys;\ sys.stderr=sys.stdout;\ py_compile.compile(r'%')\"
set efm=%C\ %.%#,%A\ \ File\ \"%f\"\\,\ line\ %l%.%#,%Z%[%^\ ]%\\@=%m
" Execute a selection of code (very cool!)
" Use VISUAL to select a range and then hit ctrl-h to execute it.
python << EOL
import vim
def EvaluateCurrentRange():
eval(compile('\n'.join(vim.current.range),'','exec'),globals())
EOL
map:py EvaluateCurrentRange()
" Use F7/Shift-F7 to add/remove a breakpoint (pdb.set_trace)
" Totally cool.
python << EOF
def SetBreakpoint():
import re
nLine = int( vim.eval( 'line(".")'))
strLine = vim.current.line
strWhite = re.search( '^(\s*)', strLine).group(1)
vim.current.buffer.append(
"%(space)spdb.set_trace() %(mark)s Breakpoint %(mark)s" %
{'space':strWhite, 'mark': '#' * 30}, nLine - 1)
for strLine in vim.current.buffer:
if strLine == "import pdb":
break
else:
vim.current.buffer.append( 'import pdb', 0)
vim.command( 'normal j1')
vim.command( 'map:py SetBreakpoint() ')
def RemoveBreakpoints():
import re
nCurrentLine = int( vim.eval( 'line(".")'))
nLines = []
nLine = 1
for strLine in vim.current.buffer:
if strLine == "import pdb" or strLine.lstrip()[:15] == "pdb.set_trace()":
nLines.append( nLine)
nLine += 1
nLines.reverse()
for nLine in nLines:
vim.command( "normal %dG" % nLine)
vim.command( "normal dd")
if nLine < nCurrentLine:
nCurrentLine -= 1
vim.command( "normal %dG" % nCurrentLine)
vim.command( "map:py RemoveBreakpoints() ")
EOF
Option 2
This setup is more like an IDE: VIM as Python IDEFriday, August 18, 2017
Learning Django (draft)
I'm learning Django with Obey the Testing Goat. This page is a draft of my miscellaneous notes.
Currently on this chapter: https://www.obeythetestinggoat.com/book/chapter_javascript.html
Currently on this chapter: https://www.obeythetestinggoat.com/book/chapter_javascript.html
My temporary development environment
Here is how I set up my tools on a computer I'm temporarily using, such as one at the library.
https://github.com
Putty
- Download putty from www.chiark.greenend.org.uk
- Putty > Window > Colours > ANSI Blue > Red: 60, Green: 60, Blue: 255
- Putty > Session > Default Settings > Save
- Save a new session with the following set:
- Session > Host Name
- Connections > Data > Auto-login username.
Vim
~/.vimrc:syntax enableNote: Superseded by Vim for Python, which is more comprehensive.
set ic
set expandtab shiftwidth=4 smarttab autoindent
Screen
~/.screenrc:shell -$SHELL
termcapinfo * ti@:te@
startup_message off
Bash
~/.bash_profile# EDITOR
export EDITOR=vim
Websites
https://www.blogger.com for note takinghttps://github.com
Subscribe to:
Posts (Atom)