text
stringlengths 4
1.08k
|
|---|
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)"
|
"add header 'WWWAuthenticate' in a flask app with value 'Basic realm=""test""'","response.headers['WWW-Authenticate'] = 'Basic realm=""test""'"
|
clear session key 'mykey',del request.session['mykey']
|
convert date string '24052010' to date object in format '%d%m%Y',"datetime.datetime.strptime('24052010', '%d%m%Y').date()"
|
Replace non-ASCII characters in string `text` with a single space,"re.sub('[^\\x00-\\x7F]+', ' ', text)"
|
Get a list `myList` from 1 to 10,myList = [i for i in range(10)]
|
use regex pattern '((.+?)\\2+)' to split string '44442(2)2(2)44',[m[0] for m in re.compile('((.+?)\\2+)').findall('44442(2)2(2)44')]
|
use regular expression '((\\d)(?:[()]*\\2*[()]*)*)' to split string `s`,"[i[0] for i in re.findall('((\\d)(?:[()]*\\2*[()]*)*)', s)]"
|
remove the space between subplots in matplotlib.pyplot,"fig.subplots_adjust(wspace=0, hspace=0)"
|
Reverse list `x`,x[::-1]
|
write a list of strings `row` to csv object `csvwriter`,csvwriter.writerow(row)
|
Jinja2 formate date `item.date` accorto pattern 'Y M d',{{(item.date | date): 'Y M d'}}
|
"Split a string `text` with comma, question mark or exclamation by non-consuming regex using look-behind","re.split('(?<=[\\.\\?!]) ', text)"
|
create a regular expression object with the pattern '\xe2\x80\x93',re.compile('\xe2\x80\x93')
|
declare an array `variable`,variable = []
|
declare an array with element 'i',intarray = array('i')
|
"given list `to_reverse`, reverse the all sublists and the list itself",[sublist[::-1] for sublist in to_reverse[::-1]]
|
"unescape special characters without splitting data in array of strings `['I ', u'<', '3s U ', u'&', ' you luvz me']`",""""""""""""".join(['I ', '<', '3s U ', '&', ' you luvz me'])"
|
disable logging while running unit tests in python django,logging.disable(logging.CRITICAL)
|
adding url `url` to mysql row,"cursor.execute('INSERT INTO index(url) VALUES(%s)', (url,))"
|
convert column of date objects 'DateObj' in pandas dataframe `df` to strings in new column 'DateStr',df['DateStr'] = df['DateObj'].dt.strftime('%d%m%Y')
|
split string `s` by '@' and get the first element,s.split('@')[0]
|
drop rows of dataframe `df` whose index is smaller than the value of `start_remove` or bigger than the value of`end_remove`,df.query('index < @start_remove or index > @end_remove')
|
Drop the rows in pandas timeseries `df` from the row containing index `start_remove` to the row containing index `end_remove`,df.loc[(df.index < start_remove) | (df.index > end_remove)]
|
Get the number of NaN values in each column of dataframe `df`,df.isnull().sum()
|
reset index of dataframe `df`so that existing index values are transferred into `df`as columns,df.reset_index(inplace=True)
|
generate a list containing values associated with the key 'value' of each dictionary inside list `list_of_dicts`,[x['value'] for x in list_of_dicts]
|
convert numpy array into python list structure,"np.array([[1, 2, 3], [4, 5, 6]]).tolist()"
|
"converting string '(1,2,3,4)' to a tuple","ast.literal_eval('(1,2,3,4)')"
|
keep a list `dataList` of lists sorted as it is created by second element,dataList.sort(key=lambda x: x[1])
|
remove duplicated items from list of lists `testdata`,"list(map(list, set(map(lambda i: tuple(i), testdata))))"
|
uniqueness for list of lists `testdata`,[list(i) for i in set(tuple(i) for i in testdata)]
|
"in django, check if a user is in a group 'Member'",return user.groups.filter(name='Member').exists()
|
"check if a user `user` is in a group from list of groups `['group1', 'group2']`","return user.groups.filter(name__in=['group1', 'group2']).exists()"
|
Change log level dynamically to 'DEBUG' without restarting the application,logging.getLogger().setLevel(logging.DEBUG)
|
"Concat each values in a tuple `(34.2424, -64.2344, 76.3534, 45.2344)` to get a string",""""""""""""".join(str(i) for i in (34.2424, -64.2344, 76.3534, 45.2344))"
|
swap each pair of characters in string `s`,""""""""""""".join([s[x:x + 2][::-1] for x in range(0, len(s), 2)])"
|
save current figure to file 'graph.png' with resolution of 1000 dpi,"plt.savefig('graph.png', dpi=1000)"
|
delete items from list `my_list` if the item exist in list `to_dell`,my_list = [[x for x in sublist if x not in to_del] for sublist in my_list]
|
find all the elements that consists value '1' in a list of tuples 'a',[item for item in a if 1 in item]
|
find all elements in a list of tuples `a` where the first element of each tuple equals 1,[item for item in a if item[0] == 1]
|
Get the index value in list `p_list` using enumerate in list comprehension,"{p.id: {'id': p.id, 'position': ind} for ind, p in enumerate(p_list)}"
|
load a file `file.py` into the python console,"exec(compile(open('file.py').read(), 'file.py', 'exec'))"
|
SQLAlchemy count the number of rows in table `Congress`,rows = session.query(Congress).count()
|
Execute Shell Script from python with variable,"subprocess.call(['test.sh', str(domid)])"
|
read excel file `file_name` using pandas,"dfs = pd.read_excel(file_name, sheetname=None)"
|
unpack the binary data represented by the hexadecimal string '4081637ef7d0424a' to a float,"struct.unpack('d', binascii.unhexlify('4081637ef7d0424a'))"
|
Get index of numpy array `a` with another numpy array `b`,a[tuple(b)]
|
"find all possible sequences of elements in a list `[2, 3, 4]`","map(list, permutations([2, 3, 4]))"
|
sort a list `unsorted_list` based on another sorted list `presorted_list`,"sorted(unsorted_list, key=presorted_list.index)"
|
create a dataframe `d` filled with zeros with indices from 0 to length of `data` and column names from `feature_list`,"d = pd.DataFrame(0, index=np.arange(len(data)), columns=feature_list)"
|
find the index of sub string 'World' in `x`,x.find('World')
|
find the index of sub string 'Aloha' in `x`,x.find('Aloha')
|
find the index of sub string 'cc' in string 'sdfasdf','sdfasdf'.index('cc')
|
find the index of sub string 'df' in string 'sdfasdf','sdfasdf'.index('df')
|
find the index of sub string 'a' in string `str`,str.find('a')
|
find the index of sub string 'g' in string `str`,str.find('g')
|
find the index of sub string 's' in string `str` starting from index 11,"str.find('s', 11)"
|
find the index of sub string 's' in string `str` starting from index 15,"str.find('s', 15)"
|
find the index of sub string 's' in string `str` starting from index 16,"str.find('s', 16)"
|
find the index of sub string 's' in string `str` starting from index 11 and ending at index 14,"str.find('s', 11, 14)"
|
sort list of date strings 'd',"sorted(d, key=lambda x: datetime.datetime.strptime(x, '%m-%Y'))"
|
Get all the sentences from a string `text` using regex,"re.split('\\.\\s', text)"
|
get all characters in string 'foobar' up to the fourth index,"""""""foobar""""""[:4]"
|
cut a string by delimiter '&',s.rfind('&')
|
cut a string using delimiter '&',s[:s.rfind('&')]
|
find a tag `option` whose `value` attribute is `state` in selenium,"driver.find_element_by_xpath(""//option[@value='"" + state + ""']"").click()"
|
"append line ""appended text"" to file ""test.txt""","with open('test.txt', 'a') as myfile:
|
myfile.write('appended text')"
|
"append line ""cool beans..."" to file ""foo""","with open('foo', 'a') as f:
|
f.write('cool beans...')"
|
append to file 'test1' content 'koko',"with open('test1', 'ab') as f:
|
pass"
|
append to file 'test' content 'koko',"open('test', 'a+b').write('koko')"
|
split string 'x+13.5*10x-4e1' into tokens,"print([i for i in re.split('([\\d.]+|\\W+)', 'x+13.5*10x-4e1') if i])"
|
Find all Chinese characters in string `ipath`,"re.findall('[\u4e00-\u9fff]+', ipath)"
|
split string `s` by letter 's',s.split('s')
|
run shell command 'rm -r some.file' in the background,"subprocess.Popen(['rm', '-r', 'some.file'])"
|
convert a list of dictionaries `listofdict into a dictionary of dictionaries,"dict((d['name'], d) for d in listofdict)"
|
print current date and time in a regular format,datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
|
print current date and time in a regular format,time.strftime('%Y-%m-%d %H:%M')
|
find consecutive consonants in a word `CONCENTRATION` using regex,"re.findall('[bcdfghjklmnpqrstvwxyz]+', 'CONCERTATION', re.IGNORECASE)"
|
get a list of indices of non zero elements in a list `a`,"[i for i, e in enumerate(a) if e != 0]"
|
get multiple integer values from a string 'string1',"map(int, re.findall('\\d+', string1))"
|
get the path of Python executable under windows,os.path.dirname(sys.executable)
|
move an x-axis label to the top of a plot `ax` in matplotlib,ax.xaxis.set_label_position('top')
|
move x-axis to the top of a plot `ax`,ax.xaxis.tick_top()
|
Move x-axis of the pyplot object `ax` to the top of a plot in matplotlib,ax.xaxis.set_ticks_position('top')
|
parse string '2015/01/01 12:12am' to DateTime object using format '%Y/%m/%d %I:%M%p',"datetime.strptime('2015/01/01 12:12am', '%Y/%m/%d %I:%M%p')"
|
Open image 'picture.jpg',"img = Image.open('picture.jpg')
|
img.show()"
|
"Open image ""picture.jpg""","img = Image.open('picture.jpg')
|
Img.show"
|
terminate the script using status value 0,sys.exit(0)
|
abort the execution of the script using message 'aa! errors!',sys.exit('aa! errors!')
|
abort the execution of a python script,sys.exit()
|
find maximum with lookahead = 4 in a list `arr`,"[max(abs(x) for x in arr[i:i + 4]) for i in range(0, len(arr), 4)]"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.