Working Ninja
2019-06-06T20:49:55

A situation arose where I was unable to use nc to send some metrics to a local Graphite server. Thanksfully, Python was installed (albeit, quite a dated version) that allowed me to set up a socket to send the data over the wire.

import commands
import socket
import time


def get_device_stats(device):
    # Retrieve 1 second average from `iostat` for device.
    status, output = commands.getstatusoutput('iostat 1 2 -kd -p /dev/%s | awk NR==7' % device)
    values = output.split()
    timestamp = int(time.time())

    send_metric(device, 'iops', values[1], timestamp)
    send_metric(device, 'read', values[2], timestamp)
    send_metric(device, 'write', values[3], timestamp)


def send_metric(device, metric, value, timestamp):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('1.2.3.4', 2003))
    # New-line character is important here, otherwise Graphite will not parse the sent data.
    s.sendall('disks.%s.%s.total %s %s\n' % (device, metric, value, timestamp))
    s.close()


devices = ['sda', 'sdb', 'sdc']

for device in devices:
    get_device_stats(device)

 

2019-02-27T21:06:20

Take the following HTML snippet:

<ul>
    <li></li>
    <li></li>
    <li></li>
    <li>Second to Last</li>
    <li></li>
</ul>

We would like to select the second to last list item (<li>). Here's how we'd go about doing that:

ul li:nth-last-child(2) { color: blue; }

Or, the inverse (everything but the second to last element):

ul li:not(:nth-last-child(2)) { color: red; }
2019-01-26T09:36:57

Objective: Sort dictionary by nested dictionary value

Let's say we want to sort the following JSON by the nested dictionary value of count.

{
  "Mail": {
    "count": 20,
    "users": ["lukeskywalker", "darthvader"]
  },
  "Droid Sync": {
    "count": 5,
    "users": ["lukeskywalker"]
  }
}

Method 1: lambda

apps_sorted = sorted(apps.items(), key=lambda x: (x[1]['count']))

Method 2: key function

def sort_by_count(x):
    # key=lambda x: (x[1]['count'])
    key, data = x
    return data['count']

apps_sorted = sorted(apps.items(), key=sort_by_count)

Source: https://stackoverflow.com/questions/4110665/sort-nested-dictionary-by-value-and-remainder-by-another-value-in-python

2018-12-21T07:46:50

First, list the shares available from the server:

smbclient -L <server> -U <user>

Next, make sure cifs-utils is available (so we can pass in the credentials option):

sudo apt install cifs-utils

Finally, add the desired share to /etc/fstab:

//ip/share /mnt/point cifs vers=3,credentials=/path/to/credentials,noexec 0 0
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.