Working Ninja
2018-11-27T07:37:07

Email contents of a file:

echo -e "Subject: subject\n\n" | cat - /file | sendmail address

Email stdout:

output=`cmd` 
echo -e "Subject: subject\n\n$output" | sendmail address
2018-10-31T20:18:39

Here's a simple shell wrapper that prints all sockets opened by Firefox.

1. Add the following function to your ~/.bashrc:

function ffsocks() {
    netstat -anp --inet | awk '/firefox/ { print $5 }'
}

2. Reload your shell (or run source ~/.bashrc) to make ffsocks callable from your shell environment.

3. Finally, execute ffsocks!

$ ffsocks
8.8.8.8:443
8.8.4.4:80

The power of shell wrappers comes from their ability to "codify" a more complex command (or series of commands, what flags are used, etc) and also in their reusable nature (we can call ffsocks any time we want!). Thus, shell wrappers are a good option for complex commands that are called often (or for those hard to remember ones that you don't call too often--I guess they're just all around good to use whenever!).

2018-09-26T20:30:58

By default, a ModelForm is populated with all its objects from the database. Sometimes it's desirable to limit these results as they are returned to the view. After setting up our ModelForm (forms.py) there is only one thing we need to do to make this happen. Within our view (views.py), we update the queryset as follows:

# forms.py
class PollForm(ModelForm):
    class Meta:
        model = Poll
        fields = ('question',)

# views.py
form = PollForm()
form.fields['question'].queryset = Poll.objects.filter(question__startswith="How")

This will filter Polls that start with "How".

Source: http://www.wkoorts.com/wkblog/2009/08/10/pre-populate-django-modelform-with-specific-queryset/

2018-08-19T10:29:23

The following example looks for the "idle" time before backlight brightness is reduced.

Find what you're looking for:

gsettings list-recursively | grep idle

Get the value:

gsettings get org.gnome.settings-daemon.plugins.power idle-brightness

Set the value:

gsettings set org.gnome.settings-daemon.plugins.power idle-brightness 120

 

2018-08-19T10:21:07

Create unicode string "a".

>>> a = u'\u2019'
>>> a
u'\u2019'

Convert to ASCII string (ASCII is default for Python 2 str()).

>>> str(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 0: ordinal not in range(128)

Encode the unicode string to UTF-8 (overriding the default of ASCII).

>>> str(a.encode('utf-8'))
'\xe2\x80\x99'
>>> print str(a.encode('utf-8'))
’

For a greater understanding, see Ned Batchelder's great "Pragmatic Unicode, or, How do I stop the pain?" (2012) video.

2018-07-27T22:37:04

Let's say we want to query our Polls app for all Questions that have popular (more than 5 votes) choices that contain Python in the choice_text.

We could query our database as follows:

SELECT * FROM question JOIN (SELECT * FROM choice WHERE vote_count > 5 AND choice_text LIKE '%Python%') choice ON question.id = choice.question_id;

Or, it can be codified in a potentially more comprehendable, OOP/ORM format with SQLAlchemy.

First, we set up our schema by declaring the relationship and the parameters of the join:

class Question(Base):
    __tablename__ = 'question'

    id = Column(Integer, primary_key=True)

    popular_choices = relationship('Choice', primaryjoin='and_(Question.id == Choice.question_id, Choice.vote_count > 5')

Next, we query with SQLAlchemy's ORM:

popular_python_choices = session.query(Question) \
    .filter(Question.popular_choices.contains('Python') \
    .all()

Not quite as terse as straight SQL but hopefully it is clear how, after the schema is set up, calling Question.popular_choices.contains('Python') provides increased readability (reads like English) and reusability (replace our filter Python with whatever you wish!).

SQLAlchemy provides another good example.

2018-07-25T21:21:23

Here's the most straightforward and succinct way I've found to mock patch a function that returns different (but specific) results with each call, shamelessly copied from Python Docs:

>>> values = {'a': 1, 'b': 2, 'c': 3}
>>> def side_effect(arg):
...     return values[arg]
...
>>> mock.side_effect = side_effect
>>> mock('a'), mock('b'), mock('c')
(1, 2, 3)

And, now that we have our side_effect function defined, we can pass new values to return:

>>> mock.side_effect = [5, 4, 3, 2, 1]
>>> mock(), mock(), mock()
(5, 4, 3)

Source: https://docs.python.org/3/library/unittest.mock.html#quick-guide

2018-06-29T20:53:23

After updating mysql-connector-python to 8.0.11 (released April 19, 2018), I received an "OperationalError: 1043 (08S01): Bad handshake" error when querying a MySQL database. I found that I needed to set 'use_pure: True' in the connection string.

From the MySQL folks:

The C extension was added in version 2.1.1 and is enabled by default as of 8.0.11. The use_pure option determines whether the Python or C version of this connector is enabled and used.1

For example2:

import mysql.connector

config = {
  'user': 'scott',
  'password': 'password',
  'host': '127.0.0.1',
  'database': 'employees',
  'use_pure': True,
}

cnx = mysql.connector.connect(**config)

Since I don't have the C extension installed on my server, I reverted back to the Python implementation. Though it is good to know that the C extension can improve performance for large queries--something to tuck away for future use.

Sources:
1https://dev.mysql.com/doc/connector-python/en/connector-python-cext.html
2https://dev.mysql.com/doc/connector-python/en/connector-python-example-connecting.html
 

2018-05-03T17:26:20

Toggle all <option>'s as checked/unchecked with the click of a <button>.

<select>
    <option></option>
    <option></option>
    <option></option>
</select>

<button></button>
jQuery("button").click(function(){
    jQuery("select :checkbox").each(function(){
        this.checked = !this.checked;
    });
});

Source: https://stackoverflow.com/questions/4177159/toggle-checkboxes-on-off

2018-04-22T10:50:51

If you've ever touched a date or time related field via the Django API, you'll have noticed the big warning that the date and/or time is not localized. While the warning is nice there isn't much more in the way of how to localize the time. Here are two ways that I usually go about it:

>>> timezone.make_aware() 
>>> timezone.localtime()

Both are found in django.utils's timezone module. If you're using Django Extensions, timezone is already loaded when you run ./manage.py shell_plus. If you're not, simply run from django.utils import timezone.

For usage:

>>> help(timezone.make_aware)
>>> help(timezone.localtime)