text
stringlengths
4
1.08k
zip lists in python,"zip([1, 2], [3, 4])"
append tuples to a tuples,"(1, 2), (3, 4), (5, 6), (8, 9), (0, 0)"
convert string to json using python,print(d['glossary']['title'])
how can i write a list of lists into a txt file?,"[[0, 1, 2, 3, 4], ['A', 'B', 'C', 'D', 'E'], [0, 1, 2, 3, 4]]"
pandas to_csv call is prepending a comma,"df.to_csv('c:\\data\\t.csv', index=False)"
unpivot first 2 columns into new columns 'year' and 'value' from a pandas dataframe `x`,"pd.melt(x, id_vars=['farm', 'fruit'], var_name='year', value_name='value')"
similarity of lists in python - comparing customers according to their features,"[[3, 1, 2], [1, 3, 1], [2, 1, 3]]"
numpy: find index of elements in one array that occur in another array,"np.searchsorted(A, np.intersect1d(A, B))"
"insert records in bulk from ""table1"" of ""master"" db to ""table1"" of sqlite3 `cursor` object",cursor.execute('INSERT OR REPLACE INTO master.table1 SELECT * FROM table1')
how to print particular json value in python?,a['Z'][0]['A']
django redirect to root from a view,redirect('Home.views.index')
post request url `url` with parameters `payload`,"r = requests.post(url, data=payload)"
return the decimal value for each hex character in data `data`,print(' '.join([str(ord(a)) for a in data]))
get indexes of the largest `2` values from a list `a` using itemgetter,"zip(*sorted(enumerate(a), key=operator.itemgetter(1)))[0][-2:]"
writing multi-line strings into cells using openpyxl,workbook.close()
adding alpha channel to rgb array using numpy,"numpy.dstack((your_input_array, numpy.zeros((25, 54))))"
how to continuously display python output in a webpage?,app.run(debug=True)
change flask security register url to `/create_account`,app.config['SECURITY_REGISTER_URL'] = '/create_account'
converting a list to a string,file2.write(' '.join(buffer))
round number 7.005 up to 2 decimal places,"round(7.005, 2)"
python: how to suppress logging statements from third party libraries?,logging.basicConfig()
django: parse json in my template using javascript,json.dumps(geodata)
how do i print colored output to the terminal in python?,"print(""All normal prints after 'RESET' above."")"
calculating cubic root in python,(1 + math.cos(i)) ** (1 / 3.0)
abort the execution of a python script,sys.exit()
"how to get value on a certain index, in a python list?","dictionary = dict([(List[i], List[i + 1]) for i in range(0, len(List), 2)])"
how do i execute a program from python? os.system fails due to spaces in path,"os.system('""C://Temp/a b c/Notepad.exe""')"
how to use regex with optional characters in python?,"print(re.match('(\\d+(\\.\\d+)?)', '3434').group(1))"
setting an item in nested dictionary with __setitem__,tmp['alpha'] = 'bbb'
syntax for creating a dictionary into another dictionary in python,"d['dict3'] = {'spam': 5, 'ham': 6}"
remove all occurrences of several chars from a string,"""""""::2012-05-14 18:10:20.856000::"""""".translate(None, ' -.:')"
convert binary string to numpy array,"np.fromstring('\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@', dtype='<f4')"
socket trouble in python,"sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)"
append element to a list inside nested list - python,"[['google', ['http://google.com']], ['computing', ['http://acm.org']]]"
calcuate mean for selected rows for selected columns in pandas data frame,"df[['b', 'c']].iloc[[2, 4]]"
python: sorting items in a dictionary by a part of a key?,"sorted(list(d.items()), key=lambda name_num: (name_num[0].rsplit(None, 1)[0], name_num[1]))"
pop multiple items from the beginning and end of a list,"['c', 'd', 'e', 'f', 'g']"
how to click an element visible after hovering with selenium?,"driver.execute_script('$(""span.info"").click();')"
numpy array broadcasting with different dimensions,"v.dot(np.rollaxis(a, 2, 1))"
convert json array `array` to python object,data = json.loads(array)
append tuples to a list,"[['AAAA', 1.11], ['BBB', 2.22], ['CCCC', 3.33]]"
pandas select from dataframe using startswith,"s.loc[s.str.startswith('a', na=False)]"
how to erase the file contents of text file in python?,"open('filename', 'w').close()"
matrix mirroring in python,"np.concatenate((A[::-1, :], A), axis=0)"
"check if the value of the key ""name"" is ""test"" in a list of dictionaries `label`",any(d['name'] == 'Test' for d in label)
printing bit representation of numbers in python,"""""""{0:16b}"""""".format(4660)"
python multidimensional arrays - most efficient way to count number of non-zero entries,sum(1 for row in rows for i in row if i)
regex to allow safe characters,"""""""^[A-Za-z0-9._~()'!*:@,;+?-]*$"""""""
how to update a plot with python and matplotlib,plt.draw()
how to delete a record in django models?,SomeModel.objects.filter(id=id).delete()
pythonic way to split a list into first and rest?,"first, rest = l[0], l[1:]"
applying regex to a pandas dataframe,df['Season'].str[:4].astype(int)
sorting a list in python,"sorted([-5, 2, 1, -8], key=abs)"
how to print unicode character in python?,print('\u0420\u043e\u0441\u0441\u0438\u044f')
find all records from collection `collection` without extracting mongo id `_id`,"db.collection.find({}, {'_id': False})"
"create a list `matrix` containing 5 lists, each of 5 items all set to 0",matrix = [([0] * 5) for i in range(5)]
input an integer tuple from user,"tuple(map(int, input().split(',')))"
how to convert a pandas dataframe subset of columns and rows into a numpy array?,"df[df['c'] > 0.5][['b', 'e']].values"
numpy isnan() fails on an array of floats (from pandas dataframe apply),"np.isnan(np.array([np.nan, 0], dtype=np.float64))"
open a text file using notepad as a help file in python?,os.startfile('file.txt')
error 404 when trying to set up a bottle-powered web app on apache/mod_wsgi,app = bottle.Bottle()
"split string 'a b.c' on space "" "" and dot character "".""","re.split('[ .]', 'a b.c')"
convert a date string '2013-1-25' in format '%y-%m-%d' to different format '%-m/%d/%y',"datetime.datetime.strptime('2013-1-25', '%Y-%m-%d').strftime('%-m/%d/%y')"
python: finding lowest integer,x = min(float(s) for s in l)
how to plot a wav file,plt.show()
using lxml to parse namepaced html?,"print(link.attrib.get('title', 'No title'))"
saving a numpy array with mixed data,"numpy.savetxt('output.dat', my_array.reshape((4, 2)), fmt='%f %i')"
creating a unicode xml from scratch with python 3.2,"tree.write('c.xml', encoding='utf-8')"
python: sorting dictionary of dictionaries,"sorted(dic, key=lambda k: dic[k]['Fisher'])"
single line nested for loops,"[(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]"
how can i zip file with a flattened directory structure using zipfile in python?,"archive.write(pdffile, os.path.basename(pdffile))"
find the position of difference between two strings,[i for i in range(len(s1)) if s1[i] != s2[i]]
recursively go through all subdirectories and files in `rootdir`,"for (root, subFolders, files) in os.walk(rootdir):
pass"
check if dictionary `subset` is a subset of dictionary `superset`,all(item in list(superset.items()) for item in list(subset.items()))
apply jinja2 filters `forceescape` and `linebreaks` on variable `my_variable`,{{my_variable | forceescape | linebreaks}}
"set size of `figure` to landscape a4 i.e. `11.69, 8.27` inches","figure(figsize=(11.69, 8.27))"
"convert a flat list into a list of tuples of every two items in the list, in order","print(zip(my_list[0::2], my_list[1::2]))"
how can i get pyplot images to show on a console app?,matplotlib.pyplot.show()
python mysqldb typeerror: not all arguments converted during string formatting,"cur.execute(""SELECT * FROM records WHERE email LIKE '%s'"", search)"
"how to make a python script which can logoff, shutdown, and restart a computer?","subprocess.call(['shutdown', '/s'])"
import all classes from module `some.package`,globals().update(importlib.import_module('some.package').__dict__)
"convert a list 'a' to a dictionary where each even element represents the key to the dictionary, and the following odd element is the value","b = {a[i]: a[i + 1] for i in range(0, len(a), 2)}"
what's the maximum number of repetitions allowed in a python regex?,"re.search('a{1,65536}', 'aaa')"
how can i capture all exceptions from a wxpython application?,app.MainLoop()
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)]"
selenium testing without browser,driver = webdriver.Firefox()
pygobject center window `window`,window.set_position(Gtk.WindowPosition.CENTER)
converting html to text with python,print(soup.get_text())
access an arbitrary value from dictionary `dict`,next(iter(list(dict.values())))
pandas : use groupby on each element of list,df['categories'].apply(pd.Series).stack().value_counts()
what's the easiest way to convert a list of hex byte strings to a list of hex integers?,"[int(x, 16) for x in L]"
flatten a tuple `l`,"[(a, b, c) for a, (b, c) in l]"
remove a key 'key' from a dictionary `my_dict`,"my_dict.pop('key', None)"
how to calculate cumulative normal distribution in python,norm.ppf(norm.cdf(1.96))
how can i do a batch insert into an oracle database using python?,connection.commit()
python - locating the position of a regex match in a string?,"re.search('\\bis\\b', String).start()"
how to make good reproducible pandas examples,df.groupby('A').sum()
how to switch two elements in string using python regex?,"pattern.sub('A*\\3\\2\\1*', s)"
flask get value of request variable 'firstname',first_name = request.args.get('firstname')