text
stringlengths
4
1.08k
how do i match contents of an element in xpath (lxml)?,"tree.xpath("".//a[text()='Example']"")[0].tag"
convert scientific notation to decimal - python,"""""""{:.50f}"""""".format(float(a[0] / a[1]))"
use operations like max/min within a row to a dataframe 'd' in pandas,"d.apply(lambda row: min([row['A'], row['B']]) - row['C'], axis=1)"
index of element in numpy array,"i, j = np.where(a == value)"
python tkinter: how to create a toggle button?,root = tk.Tk()
converting a dict into a list,"['two', 2, 'one', 1]"
sort list `my_list` in alphabetical order based on the values associated with key 'name' of each dictionary in the list,my_list.sort(key=operator.itemgetter('name'))
list of all unique characters in a string?,list(set('aaabcabccd'))
load a json data `json_string` into variable `json_data`,json_data = json.loads(json_string)
python spliting a string,"""""""Sico87 is an awful python developer"""""".split(' ')"
how to extract a floating number from a string,"re.findall('\\d+\\.\\d+', 'Current Level: 13.4 db.')"
how to get the symbolic path instead of real path?,os.path.abspath('link/file')
how to plot a rectangle on a datetime axis using matplotlib?,ax.xaxis.set_major_locator(locator)
how do i get the url of the active google chrome tab in windows?,"omniboxHwnd = win32gui.FindWindowEx(hwnd, 0, 'Chrome_OmniboxView', None)"
how to use selenium with python?,from selenium import webdriver
check python version,sys.version_info
pass another object to the main flask application,app.run()
how to store indices in a list,print([s[i] for i in index])
load a tsv file `c:/~/trainsetrel3.txt` into a pandas data frame,"DataFrame.from_csv('c:/~/trainSetRel3.txt', sep='\t')"
get a list `res_list` of the first elements of each tuple in a list of tuples `rows`,res_list = [x[0] for x in rows]
selenium / python - selecting via css selector,"driver.find_element_by_css_selector("".test_button4[value='Update']"").click()"
how can i treat a section of a file as though it's a file itself?,f.seek(0)
how to compare list in python?,result.append(b[index])
reply to tweet with tweepy - python,"api.update_status('@<username> My status update', tweetId)"
how to save xlsxwriter file in certain path?,workbook = xlsxwriter.Workbook('app/smth1/smth2/Expenses01.xlsx')
how to write a multidimensional array to a text file?,outfile.write('# New slice\n')
how to get an arbitrary element from a frozenset?,[next(iter(s)) for _ in range(10)]
"append line ""cool beans..."" to file ""foo""","with open('foo', 'a') as f:
f.write('cool beans...')"
python wildcard matching,"""""""1**0*"""""".replace('*', '[01]')"
sorting python list based on the length of the string,xs.sort(key=lambda s: len(s))
how can i get around declaring an unused variable in a for loop?,[''] * len(myList)
replacing letters in python given a specific condition,"['tuberculin 1 Cap(s)', 'tylenol 1 Cap(s)', 'tramadol 2 Cap(s)']"
how to print container object with unicode-containing values?,print(str(x).decode('raw_unicode_escape'))
matplotlib - how to plot a random-oriented rectangle (or any shape)?,plt.show()
consequences of abusing nltk's word_tokenize(sent),"nltk.tokenize.word_tokenize('Hello, world. How are you?')"
how to display a jpg file in python?,Image.open('pathToFile').show()
how to clear an entire treeview with tkinter,tree.delete(*tree.get_children())
regex: string with optional parts,"re.search('^(.*?)(Arguments:.*?)?(Returns:.*)?$', s, re.DOTALL)"
how do i connect to a mysql database in python?,cursor.execute('SELECT * FROM LOCATION')
mask out specific values from an array,"np.in1d(a, [2, 3]).reshape(a.shape)"
how to create a self resizing grid of buttons in tkinter?,root.mainloop()
how to run basic web app container in docker-py?,host_port = info['NetworkSettings']['Ports']['1337'][0]['HostPort']
filter pyspark dataframe column with none value,df.filter('dt_mvmt is not NULL')
how to iterate over unicode characters in python 3?,print('U+{:04X}'.format(ord(c)))
python - how to calculate equal parts of two dictionaries?,"dict((x, set(y) & set(d1.get(x, ()))) for x, y in d2.items())"
select rows from a dataframe based on values in a column in pandas,"df.loc[df.index.isin(['one', 'two'])]"
how do convert a pandas/dataframe to xml?,print(df.to_xml())
python - move elements in a list of dictionaries to the end of the list,"sorted(lst, key=lambda x: x['language'] != 'en')"
app engine ndb alternative for db.stringlistproperty,ndb.StringProperty(repeated=True)
elegant way to transform a list of dict into a dict of dicts,"dict(zip([d.pop('name') for d in listofdict], listofdict))"
how to install subprocess module for python?,subprocess.call(['py.test'])
add legend to scatter plot,plt.show()
turn dataframe into frequency list with two column variables in python,"pd.concat([df1, df2], axis=1)"
how to convert a string to its base-10 representation?,"int(s.encode('hex'), 16)"
split 1d array `a` into 2d array at the last element,"np.split(a, [-1])"
mapping a table function to a model using sqlalchamy,session.query(func.myThingFunction('bar')).all()
how can a python list be sliced such that a column is moved to being a separate element column?,"[item for sublist in [[i[1:], [i[0]]] for i in l] for item in sublist]"
tornado write a jsonp object,"{'1': 2, 'foo': 'bar', 'false': true}"
how to pass members of a dict to a function,some_func(**mydict)
regex - substitute specific chars exept specific string,"""""""\\1"""""""
accepting a dictionary as an argument with argparse and python,"dict(""{'key1': 'value1'}"")"
initialize a list of empty lists `x` of size 3,x = [[] for i in range(3)]
"find all possible sequences of elements in a list `[2, 3, 4]`","map(list, permutations([2, 3, 4]))"
get webpage contents with python?,urllib.request.urlopen('http://www.python.org/')
is it possible to renice a subprocess?,Popen(['nice']).communicate()
sort list of strings by integer suffix in python,"sorted(the_list, key=lambda k: int(k.split('_')[1]))"
python: append values to a set,"a.update([3, 4])"
python - how to sort a list of numerical values in ascending order,"sorted([10, 3, 2])"
how to match beginning of string or character in python,"re.findall('[^a]', 'abcd')"
how to pass initial parameter to django's modelform instance?,"super(BackupForm, self).__init__(*args, **kwargs)"
python: how to get the length of itertools _grouper,length = len(list(clusterList))
writing to a file in a for loop,myfile.close()
how to reorder indexed rows based on a list in pandas data frame,"df.reindex(['Z', 'C', 'A'])"
using spritesheets in tkinter,app.mainloop()
removing nan values from an array,x = x[~numpy.isnan(x)]
how to use regexp function in sqlite with sqlalchemy?,"cursor.execute('SELECT c1 FROM t1 WHERE c1 REGEXP ?', [SEARCH_TERM])"
how to iterate over a range of keys in a dictionary?,"[x for x in d if x not in ('Domain Source', 'Recommend Suppress')]"
apply a function to a pandas dataframe whose returned value is based on other rows,"df.groupby(['item', 'price']).region.apply(f)"
find the indexes of all regex matches in python?,"[(m.start(0), m.end(0)) for m in re.finditer(pattern, string)]"
plot with custom text for x axis points,plt.show()
how to draw intersecting planes?,plt.show()
turning off logging in paramiko,logging.basicConfig(level=logging.WARN)
pandas data frame indexing using loc,df['Weekday'].loc[1]
how do i create a python set with only one element?,set(['foo'])
wtforms: how to select options in selectmultiplefield?,"form.myfield.data = ['1', '3']"
string split with indices in python,"c = [(m.start(), m.end() - 1) for m in re.finditer('\\S+', a)]"
format string - spaces between every three digit,"format(12345678.46, ',').replace(',', ' ').replace('.', ',')"
read unicode characters from command-line arguments in python 2.x on windows,print(repr(sys.argv[1].decode('UTF-8')))
how to get text with selenium web driver in python,element = driver.find_element_by_class_name('class_name').text
"make a dictionary from list `f` which is in the format of four sets of ""val, key, val""","{f[i + 1]: [f[i], f[i + 2]] for i in range(0, len(f), 3)}"
conversion from a numpy 3d array to a 2d array,"a.reshape(-1, 3, 3, 3, 3, 3).transpose(0, 2, 4, 1, 3, 5).reshape(27, 27)"
pythonic way to create a 2d array?,[([0] * width) for y in range(height)]
python counting elements of a list within a list,all(x.count(1) == 3 for x in L)
"how do i randomly select a variable from a list, and then modify it in python?","['1', '2', '3', '4', '5', '6', '7', 'X', '9']"
how to send an email with gmail as provider using python?,server.starttls()
"how to reverse geocode serverside with python, json and google maps?",jsondata['results'][0]['address_components']
how to remove u from sqlite3 cursor.fetchall() in python,ar = [r[0] for r in cur.fetchall()]
how to filter only printable characters in a file on bash (linux) or python?,print('\n'.join(lines))
"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]