neulab/docprompting-conala huggingface dataset:
# convert date strings in pandas dataframe column`df['date']` to pandas timestamps using the format '%d%b%Y'
df['date'] = pd.to_datetime(df['date'], format='%d%b%Y')
# force bash interpreter '/bin/bash' to be used instead of shell
os.system('GREPDB="echo 123"; /bin/bash -c "$GREPDB"')
# Run a command `echo hello world` in bash instead of shell
os.system('/bin/bash -c "echo hello world"')
# get index values of pandas dataframe `df` as list
df.index.values.tolist()
# run app `app` on host '192.168.0.58' and port 9000 in Flask
app.run(host='192.168.0.58', port=9000, debug=False)
# print unicode string `ex\xe1mple` in uppercase
print('ex\xe1mple'.upper())
# Get the sum of values to the power of their indices in a list `l`
sum(j ** i for i, j in enumerate(l, 1))
# get the first row, second column; second row, first column, and first row third column values of numpy array `arr`
arr[[0, 1, 1], [1, 0, 2]]
# Delete mulitple columns `columnheading1`, `columnheading2` in pandas data frame `yourdf`
yourdf.drop(['columnheading1', 'columnheading2'], axis=1, inplace=True)
# Django get first 10 records of model `User` ordered by criteria 'age' of model 'pet'
User.objects.order_by('-pet__age')[:10]
# print bold text 'Hello'
print('\x1b[1m' + 'Hello')
# run python script 'script2.py' from another python script, passing in 1 as an argument
os.system('script2.py 1')
# create new column `A_perc` in dataframe `df` with row values equal to the value in column `A` divided by the value in column `sum`
df['A_perc'] = df['A'] / df['sum']
# list duplicated elements in two lists `listA` and `listB`
list(set(listA) & set(listB))
# extract digits in a simple way from a python string
map(int, re.findall('\\d+', s))
# find overlapping matches from a string `hello` using regex
re.findall('(?=(\\w\\w))', 'hello')
# Python / Remove special character from string
re.sub('[^a-zA-Z0-9-_*.]', '', my_string)
# Sort list `keys` based on its elements' dot-seperated numbers
keys.sort(key=lambda x: map(int, x.split('.')))
# Sort a list of integers `keys` where each value is in string format
keys.sort(key=lambda x: [int(y) for y in x.split('.')])
# get the tuple in list `a_list` that has the largest item in the second index
max_item = max(a_list, key=operator.itemgetter(1))
# find tuple in list of tuples `a_list` with the largest second element
max(a_list, key=operator.itemgetter(1))
# wait for shell command `p` evoked by  subprocess.Popen to complete
p.wait()
# replace white spaces in dataframe `df` with '_'
df.replace(' ', '_', regex=True)
# switch positions of each two adjacent characters in string `a`
print(''.join(''.join(i) for i in zip(a2, a1)) + a[-1] if len(a) % 2 else '')
# Python: Extract numbers from a string
[int(s) for s in re.findall('\\b\\d+\\b', "he33llo 42 I'm a 32 string 30")]
# remove extra white spaces & tabs from a string `s`
""" """.join(s.split())
# get value of key `post code` associated with first index of key `places` of dictionary `data`
print(data['places'][0]['post code'])
# get a list of indices of non zero elements in a list `a`
[i for i, e in enumerate(a) if e != 0]
# Define a list with string values `['a', 'c', 'b', 'obj']`
a, c, b, obj
# repeat every character for 7 times in string 'map'
"""""".join(map(lambda x: x * 7, 'map'))
# restart a computer after `900` seconds using subprocess
subprocess.call(['shutdown', '/r', '/t', '900'])
# logoff computer having windows operating system using python
subprocess.call(['shutdown', '/l '])
# recursively delete all contents in directory `path`
shutil.rmtree(path, ignore_errors=False, onerror=None)
# convert pandas DataFrame `df` to a dictionary using `id` field as the key
df.set_index('id').to_dict()
# convert pandas dataframe `df` with fields 'id', 'value' to dictionary
df.set_index('id')['value'].to_dict()
# create list `new_list` containing the last 10 elements of list `my_list`
new_list = my_list[-10:]
# get the last 10 elements from a list `my_list`
my_list[-10:]
# Run 'test2.py' file with python location 'path/to/python' and arguments 'neededArgumetGoHere' as a subprocess
call(['path/to/python', 'test2.py', 'neededArgumetGoHere'])
# parse date string '2009/05/13 19:19:30 -0400' using format '%Y/%m/%d %H:%M:%S %z'
datetime.strptime('2009/05/13 19:19:30 -0400', '%Y/%m/%d %H:%M:%S %z')
# make new column 'C' in panda dataframe by adding values from other columns 'A' and 'B'
df['C'] = df['A'] + df['B']
# sum the length of lists in list `x` that are more than 1 item in length
sum(len(y) for y in x if len(y) > 1)
# Normalize line ends in a string 'mixed'
mixed.replace('\r\n', '\n').replace('\r', '\n')
# replace each occurrence of the pattern '(http://\\S+|\\S*[^\\w\\s]\\S*)' within `a` with ''
re.sub('(http://\\S+|\\S*[^\\w\\s]\\S*)', '', a)
# check if dictionary `subset` is a subset of dictionary `superset`
all(item in list(superset.items()) for item in list(subset.items()))
# Save plot `plt` as svg file 'test.svg'
plt.savefig('test.svg')
# check if elements in list `my_list` are coherent in order
return my_list == list(range(my_list[0], my_list[-1] + 1))
# decode encodeuricomponent in GAE
urllib.parse.unquote(h.path.encode('utf-8')).decode('utf-8')
# remove items from dictionary `myDict` if the item's value `val` is equal to 42
myDict = {key: val for key, val in list(myDict.items()) if val != 42}
# Remove all items from a dictionary `myDict` whose values are `42`
{key: val for key, val in list(myDict.items()) if val != 42}
# read the first line of a string `my_string`
my_string.splitlines()[0]
# How do I read the first line of a string?
my_string.split('\n', 1)[0]
# extracting column `1` and `9` from array `data`
data[:, ([1, 9])]
# serve a static html page 'your_template.html' at the root of a django project
url('^$', TemplateView.as_view(template_name='your_template.html'))
# return the conversion of decimal `d` to hex without the '0x' prefix
hex(d).split('x')[1]
# Get multiple matched strings using regex pattern `(?:review: )?(http://url.com/(\\d+))\\s?`
pattern = re.compile('(?:review: )?(http://url.com/(\\d+))\\s?', re.IGNORECASE)
# get count of values in numpy array `a` that are between values `25` and `100`
((25 < a) & (a < 100)).sum()
# replace only first occurence of string `TEST` from a string `longlongTESTstringTEST`
'longlongTESTstringTEST'.replace('TEST', '?', 1)
# format current date to pattern '{%Y-%m-%d %H:%M:%S}'
time.strftime('{%Y-%m-%d %H:%M:%S}')
# count the number of pairs in dictionary `d` whose value equal to `chosen_value`
sum(x == chosen_value for x in list(d.values()))
# count the number of values in `d` dictionary that are predicate to function `some_condition`
sum(1 for x in list(d.values()) if some_condition(x))
# Get absolute folder path and filename for file `existGDBPath `
os.path.split(os.path.abspath(existGDBPath))
# extract folder path from file path
os.path.dirname(os.path.abspath(existGDBPath))
# align values in array `b` to the order of corresponding values in array `a`
a[np.in1d(a, b)]
# Join pandas data frame `frame_1` and `frame_2` with left join by `county_ID` and right join by `countyid`
pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')
# Python JSON encoding
json.dumps({'apple': 'cat', 'banana': 'dog', 'pear': 'fish'})
# get key-value pairs in dictionary `my_dictionary` for all keys in list `my_list` in the order they appear in `my_list`
dict(zip(my_list, map(my_dictionary.get, my_list)))
# sort json `ips_data` by a key 'data_two'
sorted_list_of_keyvalues = sorted(list(ips_data.items()), key=item[1]['data_two'])
# remove empty strings from list `str_list`
str_list = list([_f for _f in str_list if _f])
# do a `left` merge of dataframes `x` and `y` on the column `state` and sort by `index`
x.reset_index().merge(y, how='left', on='state', sort=False).sort('index')
# Confirm urls in Django properly
url('^$', include('sms.urls')),
# sort a list of dictionary `persons` according to the key `['passport']['birth_info']['date']`
sorted(persons, key=lambda x: x['passport']['birth_info']['date'])
# flatten list of tuples `a`
list(chain.from_iterable(a))
# change the background colour of the button `pushbutton` to red
self.pushButton.setStyleSheet('background-color: red')
# Change log level dynamically to 'DEBUG' without restarting the application
logging.getLogger().setLevel(logging.DEBUG)
# resample series `s` into 3 months bins and sum each bin
s.resample('3M', how='sum')
# Set colorbar range from `0` to `15` for pyplot object `quadmesh` in matplotlib
quadmesh.set_clim(vmin=0, vmax=15)
# check if all boolean values in a python dictionary `dict` are true
all(dict.values())
# return a random word from a word list 'words'
print(random.choice(words))
# extract floating number from string 'Current Level: 13.4 db.'
re.findall('\\d+\\.\\d+', 'Current Level: 13.4 db.')
# extract floating point numbers from a string 'Current Level: -13.2 db or 14.2 or 3'
re.findall('[-+]?\\d*\\.\\d+|\\d+', 'Current Level: -13.2 db or 14.2 or 3')
# split string `str` with delimiter '; ' or delimiter ', '
re.split('; |, ', str)
# replace non-ascii chars from a unicode string u'm\xfasica'
unicodedata.normalize('NFKD', 'm\xfasica').encode('ascii', 'ignore')
# convert a string `a` of letters embedded in squared brackets into embedded lists
[i.split() for i in re.findall('\\[([^\\[\\]]+)\\]', a)]
# Parse DateTime object `datetimevariable` using format '%Y-%m-%d'
datetimevariable.strftime('%Y-%m-%d')
# get index of the first biggest element in list `a`
a.index(max(a))
# create dataframe `males` containing data of dataframe `df` where column `Gender` is equal to 'Male' and column `Year` is equal to 2014
males = df[(df[Gender] == 'Male') & (df[Year] == 2014)]
# get a new string from the 3rd character to the end of the string `x`
x[2:]
# get a new string including all but the last character of string `x`
x[:(-2)]
# get a new string including the last two characters of string `x`
x[(-2):]
# get a new string with the 3rd to the second-to-last characters of string `x`
x[2:(-2)]
# select alternate characters of "H-e-l-l-o- -W-o-r-l-d"
'H-e-l-l-o- -W-o-r-l-d'[::2]
# select a substring of `s` beginning at `beginning` of length `LENGTH`
s = s[beginning:(beginning + LENGTH)]
# Get a list of items in the list `container` with attribute equal to `value`
items = [item for item in container if item.attribute == value]
# Get the indices in array `b` of each element appearing in array `a`
np.in1d(b, a).nonzero()[0]
# sort a list of lists `L` by index 2 of the inner list
sorted(L, key=itemgetter(2))
# sort a list of lists `l` by index 2 of the inner list
l.sort(key=(lambda x: x[2]))
# sort list `l` by index 2 of the item
sorted(l, key=(lambda x: x[2]))
# sort a list of lists `list_to_sort` by indices 2,0,1 of the inner list
sorted_list = sorted(list_to_sort, key=itemgetter(2, 0, 1))
# Change data type of data in column 'grade' of dataframe `data_df` into float and then to int
data_df['grade'] = data_df['grade'].astype(float).astype(int)
# Delete an item with key "key" from `mydict`
mydict.pop('key', None)
# Delete an item with key `key` from `mydict`
del mydict[key]
# Delete an item with key `key` from `mydict`
try:
    del mydict[key]
except KeyError:
    pass
try:
    del mydict[key]
except KeyError:
    pass
# Get total number of values in a nested dictionary `food_colors`
sum(len(x) for x in list(food_colors.values()))
# count all elements in a nested dictionary `food_colors`
sum(len(v) for v in food_colors.values())
# concatenate sequence of numpy arrays  `LIST` into a one dimensional array along the first axis
numpy.concatenate(LIST, axis=0)
# print '[1, 2, 3]'
print('[%s, %s, %s]' % (1, 2, 3))
# Display `1 2 3` as a list of string
print('[{0}, {1}, {2}]'.format(1, 2, 3))
# read file 'myfile' using encoding 'iso-8859-1'
codecs.open('myfile', 'r', 'iso-8859-1').read()
# append `date` to list value of `key` in dictionary `dates_dict`, or create key `key` with value `date` in a list if it does not exist
dates_dict.setdefault(key, []).append(date)
# build dictionary with keys of dictionary `_container` as keys and values of returned value of function `_value` with correlating key as parameter
{_key: _value(_key) for _key in _container}
# load a tsv file `c:/~/trainSetRel3.txt` into a pandas data frame
DataFrame.from_csv('c:/~/trainSetRel3.txt', sep='\t')
# regular expression matching all but 'aa' and 'bb' for string `string`
re.findall('-(?!aa-|bb-)([^-]+)', string)
# regular expression matching all but 'aa' and 'bb'
re.findall('-(?!aa|bb)([^-]+)', string)
# click on the text button 'section-select-all' using selenium python
browser.find_element_by_class_name('section-select-all').click()
# regex for repeating words in a string `s`
re.sub('(?<!\\S)((\\S+)(?:\\s+\\2))(?:\\s+\\2)+(?!\\S)', '\\1', s)
# clear the textbox `text` in tkinter
tex.delete('1.0', END)
# get a dictionary with keys from one list `keys` and values from other list `data`
dict(zip(keys, zip(*data)))
# create a list containing the `n` next values of generator `it`
[next(it) for _ in range(n)]
# get list of n next values of a generator `it`
list(itertools.islice(it, 0, n, 1))
# convert csv file 'test.csv' into two-dimensional matrix
numpy.loadtxt(open('test.csv', 'rb'), delimiter=',', skiprows=1)
# MySQL execute query 'SELECT * FROM foo WHERE bar = %s AND baz = %s' with parameters `param1` and `param2`
c.execute('SELECT * FROM foo WHERE bar = %s AND baz = %s', (param1, param2))
# get data of columns with Null values in dataframe `df`
df[pd.isnull(df).any(axis=1)]
# Collapse hierarchical column index to level 0 in dataframe `df`
df.columns = df.columns.get_level_values(0)
# get keys with same value in dictionary `d`
print([key for key in d if d[key] == 1])
# get keys with same value in dictionary `d`
print([key for key, value in d.items() if value == 1])
# Get keys from a dictionary 'd' where the value is '1'.
print([key for key, value in list(d.items()) if value == 1])
# coalesce non-word-characters in string `a`
print(re.sub('(\\W)\\1+', '\\1', a))
# variable number of digits `digits` in variable `value` in format string "{0:.{1}%}"
"""{0:.{1}%}""".format(value, digits)
# sort list `a` in ascending order based on the addition of the second and third elements of each tuple in it
sorted(a, key=lambda x: (sum(x[1:3]), x[0]))
# sort a list of tuples `a` by the sum of second and third element of each tuple
sorted(a, key=lambda x: (sum(x[1:3]), x[0]), reverse=True)
# sorting a list of tuples `lst` by the sum of the second elements onwards, and third element of the tuple
sorted(lst, key=lambda x: (sum(x[1:]), x[0]))
# sort the list of tuples `lst` by the sum of every value except the first and by the first value in reverse order
sorted(lst, key=lambda x: (sum(x[1:]), x[0]), reverse=True)
# multiply all items in a list `[1, 2, 3, 4, 5, 6]` together
from functools import reduce
reduce(lambda x, y: x * y, [1, 2, 3, 4, 5, 6])
# create a list containing the subtraction of each item in list `L` from the item prior to it
[(y - x) for x, y in zip(L, L[1:])]
# sympy solve matrix of linear equations `(([1, 1, 1, 1], [1, 1, 2, 3]))` with variables `(x, y, z)`
linsolve(Matrix(([1, 1, 1, 1], [1, 1, 2, 3])), (x, y, z))
# replacing 'ABC' and 'AB' values in column 'BrandName' of dataframe `df` with 'A'
df['BrandName'].replace(['ABC', 'AB'], 'A')
# replace values `['ABC', 'AB']` in a column 'BrandName' of  pandas dataframe `df` with another value 'A'
df['BrandName'] = df['BrandName'].replace(['ABC', 'AB'], 'A')
# Set time zone `Europe/Istanbul` in Django
TIME_ZONE = 'Europe/Istanbul'
# match regex pattern 'TAA(?:[ATGC]{3})+?TAA' on string `seq`
re.findall('TAA(?:[ATGC]{3})+?TAA', seq)
# remove the space between subplots in matplotlib.pyplot
fig.subplots_adjust(wspace=0, hspace=0)
# convert js date object 'Tue, 22 Nov 2011 06:00:00 GMT' to python datetime
datetime.strptime('Tue, 22 Nov 2011 06:00:00 GMT', '%a, %d %b %Y %H:%M:%S %Z')
# order a list of lists `l1` by the first value
l1.sort(key=lambda x: int(x[0]))
# order a list of lists `[[1, 'mike'], [1, 'bob']]` by the first value of individual list
sorted([[1, 'mike'], [1, 'bob']])
# convert list of key-value tuples `[('A', 1), ('B', 2), ('C', 3)]` into dictionary
dict([('A', 1), ('B', 2), ('C', 3)])
# Check if 3 is not in a list [2, 3, 4]
(3 not in [2, 3, 4])
# Check if tuple (2, 3) is not in a list [(2, 3), (5, 6), (9, 1)]
((2, 3) not in [(2, 3), (5, 6), (9, 1)])
# Check if tuple (2, 3) is not in a list [(2, 7), (7, 3), "hi"]
((2, 3) not in [(2, 7), (7, 3), 'hi'])
# Check if 3 is not in the list [4,5,6]
(3 not in [4, 5, 6])
# find consecutive consonants in a word `CONCENTRATION` using regex
re.findall('[bcdfghjklmnpqrstvwxyz]+', 'CONCERTATION', re.IGNORECASE)
# add string `-` in `4th` position of a string `s`
s[:4] + '-' + s[4:]
# check if character '-' exists in a dataframe `df` cell 'a'
df['a'].str.contains('-')
# Jinja2 formate date `item.date` accorto pattern 'Y M d'
{{(item.date | date): 'Y M d'}}
# Convert long int `myNumber` into date and time represented in the the string format '%Y-%m-%d %H:%M:%S'
datetime.datetime.fromtimestamp(myNumber).strftime('%Y-%m-%d %H:%M:%S')
# remove leading and trailing zeros in the string 'your_Strip'
your_string.strip('0')
# destruct elements of list `[1, 2, 3]` to variables `a`, `b` and `c`
a, b, c = [1, 2, 3]
# get a list of characters in string `x` matching regex pattern `pattern`
print(re.findall(pattern, x))
# get a list `slice` of array slices of the first two rows and columns from array `arr`
slice = [arr[i][0:2] for i in range(0, 2)]
# Create new list `result` by splitting each item in list `words`
result = [item for word in words for item in word.split(',')]
# sort list `lst` based on each element's number of occurrences
sorted(lst, key=lambda x: (-1 * c[x], lst.index(x)))
# Insert a character `-` after every two elements in a string `s`
"""-""".join(a + b for a, b in zip(s[::2], s[1::2]))
# replace fields delimited by braces {} in string "Day old bread, 50% sale {0}" with string 'today'
"""Day old bread, 50% sale {0}""".format('today')
# zip two lists `[1, 2]` and `[3, 4]` into a list of two tuples containing elements at the same index in each list
zip([1, 2], [3, 4])
# remove all instances of parenthesesis containing text beginning with `as ` from string `line`
line = re.sub('\\(+as .*?\\) ', '', line)
# decode url `url` with utf8 and print it
print(urllib.parse.unquote(url).decode('utf8'))
# decode a urllib escaped url string `url` with `utf8`
url = urllib.parse.unquote(url).decode('utf8')
# substitute multiple whitespace with single whitespace in string `mystring`
""" """.join(mystring.split())
# How can I split and parse a string in Python?
"""2.7.0_bf4fda703454""".split('_')
# sort a list of tuples 'unsorted' based on two elements, second and third
sorted(unsorted, key=lambda element: (element[1], element[2]))
# sort list `files` based on variable `file_number`
files.sort(key=file_number)
# parse a comma-separated string number '1,000,000' into int
int('1,000,000'.replace(',', ''))
# multiply the columns of sparse matrix `m` by array `a` then multiply the rows of the resulting matrix by array `a`
numpy.dot(numpy.dot(a, m), a)
# print "Please enter something: " to console, and read user input to `var`
var = input('Please enter something: ')
# convert a set of tuples `queryresult` to a string `emaillist`
emaillist = '\n'.join(item[0] for item in queryresult)
# convert a set of tuples `queryresult` to a list of strings
[item[0] for item in queryresult]
# convert a list of tuples `queryresult` to a string from the first indexes.
emaillist = '\n'.join([item[0] for item in queryresult])
# list the contents of a directory '/home/username/www/'
os.listdir('/home/username/www/')
# Set multi index on columns 'Company' and 'date' of data frame `df` in pandas.
df.set_index(['Company', 'date'], inplace=True)
# use upper case letters to print hex value `value`
print('0x%X' % value)
# Find all Chinese characters in string `ipath`
re.findall('[\u4e00-\u9fff]+', ipath)
# parse string "Jun 1 2005  1:33PM" into datetime by format "%b %d %Y %I:%M%p"
datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')
# parse string "Aug 28 1999 12:00AM" into datetime
parser.parse('Aug 28 1999 12:00AM')
# sort list `lst` with positives coming before negatives with values sorted respectively
sorted(lst, key=lambda x: (x < 0, x))
# get tuples of the corresponding elements from lists `lst` and `lst2`
[(x, lst2[i]) for i, x in enumerate(lst)]
# create tuples containing elements that are at the same index of list `lst` and list `lst2`
[(i, j) for i, j in zip(lst, lst2)]
# get tuples from lists `lst` and `lst2` using list comprehension in python 2
[(lst[i], lst2[i]) for i in range(len(lst))]
# python, format string "{} %s {}" to have 'foo' and 'bar' in the first and second positions
"""{} %s {}""".format('foo', 'bar')
# replace string ' and ' in string `stuff` with character '/'
stuff.replace(' and ', '/')
# Execute SQL statement `sql` with values of dictionary `myDict` as parameters
cursor.execute(sql, list(myDict.values()))
# set the size of figure `fig` in inches to width height of `w`, `h`
fig.set_size_inches(w, h, forward=True)
# get value of first index of each element in list `a`
[x[0] for x in a]
# python how to get every first element in 2 dimensional list `a`
[i[0] for i in a]
# read file `fname` line by line into a list `content`
with open(fname) as f:
    content = f.readlines()
# read file 'filename' line by line into a list `lines`
with open('filename') as f:
    lines = f.readlines()
# read file 'filename' line by line into a list `lines`
lines = [line.rstrip('\n') for line in open('filename')]
# read file "file.txt" line by line into a list `array`
with open('file.txt', 'r') as ins:
    array = []
    for line in ins:
        array.append(line)
# Remove anything in parenthesis from string `item` with a regex
item = re.sub(' ?\\([^)]+\\)', '', item)
# Remove word characters in parenthesis from string `item` with a regex
item = re.sub(' ?\\(\\w+\\)', '', item)
# Remove all data inside parenthesis in string `item`
item = re.sub(' \\(\\w+\\)', '', item)
# calculate ratio of sparsity in a numpy array `a`
np.isnan(a).sum() / np.prod(a.shape)
# get digits in string `my_string`
"""""".join(c for c in my_string if c.isdigit())
# get all characters between two `$` characters in string `string`
re.findall('\\$([^$]*)\\$', string)
# getting the string between 2 '$' characters in '$sin (x)$ is an function of x'
re.findall('\\$(.*?)\\$', '$sin (x)$ is an function of x')
# get list of string elements in string `data` delimited by commas, putting `0` in place of empty strings
[(int(x) if x else 0) for x in data.split(',')]
# split string `s` into a list of strings based on ',' then replace empty strings with zero
""",""".join(x or '0' for x in s.split(','))
# get a list of the keys in each dictionary in a dictionary of dictionaries `foo`
[k for d in list(foo.values()) for k in d]
# count `True` values associated with key 'one' in dictionary `tadas`
sum(item['one'] for item in list(tadas.values()))
# remove all duplicate items from a list `lseperatedOrblist`
woduplicates = list(set(lseperatedOrblist))
# prompt string 'Press Enter to continue...' to the console
input('Press Enter to continue...')
# customize the time format in python logging
formatter = logging.Formatter('%(asctime)s;%(levelname)s;%(message)s')
# set the default encoding to 'utf-8'
sys.setdefaultencoding('utf8')
# reset index of dataframe `df`so that existing index values are transferred into `df`as columns
df.reset_index(inplace=True)
# Get all the keys from dictionary `y` whose value is `1`
[i for i in y if y[i] == 1]
# Sort list `li` in descending order based on the second element of each list inside list`li`
sorted(li, key=operator.itemgetter(1), reverse=True)
# remove false entries from a dictionary `hand`
{k: v for k, v in list(hand.items()) if v}
# Get a dictionary from a dictionary `hand` where the values are present
dict((k, v) for k, v in hand.items() if v)
# sort a nested list by the inverse of element 2, then by element 1
sorted(l, key=lambda x: (-int(x[1]), x[0]))
# get name of primary field `name` of django model `CustomPK`
CustomPK._meta.pk.name
# sort a pandas data frame according to column `Peak` in ascending and `Weeks` in descending order
df.sort_values(['Peak', 'Weeks'], ascending=[True, False], inplace=True)