text
stringlengths
4
1.08k
how to write russian characters in file?,"writefile = codecs.open('write.txt', 'w', 'utf-8')"
logging across multiple co-routines / greenlets / microthreads with gevent?,gevent.joinall(jobs)
creating a log-linear plot in matplotlib using hist2d,plt.show()
how to add http headers in suds 0.3.6?,client.set_options(headers={'key2': 'value'})
check whether elements in list `a` appear only once,len(set(a)) == len(a)
how to prevent table regeneration in ply,"yacc.yacc(debug=0, write_tables=0)"
pandas data frame plotting,df.plot(title='Title Here')
any substitutes for pexpect?,ssh.exec_command('nohup sleep 300 &')
getting a list of all subdirectories in the current directory,os.walk(directory)
how to compare two lists in python,"all(i < j for i, j in zip(a, b))"
can i restore a function whose closure contains cycles in python?,"f(*args, **kwargs)"
how to combine single and multiindex pandas dataframes,"pd.concat([df2, df1], axis=1)"
how to get first element in a list of tuples?,"[1, 2]"
numpy array multiplication with arrays of arbitrary dimensions,"np.allclose(C0, C3)"
how do i pipe the output of file to a variable in python?,"output = Popen(['mycmd', 'myarg'], stdout=PIPE).communicate()[0]"
python remove last 3 characters of a string,foo = ''.join(foo.split())
how to get the size of a string in python?,len(s)
parameters to numpy's fromfunction,"array([[0.0, 0.0], [1.0, 1.0]]), array([[0.0, 1.0], [0.0, 1.0]])"
how can i make a for-loop pyramid more concise in python?,"product(list(range(3)), list(range(4)), ['a', 'b', 'c'], some_other_iterable)"
what are the guidelines to allow customizable logging from a python module?,logger = logging.getLogger(__name__)
how can i list the contents of a directory in python?,os.listdir('/home/username/www/')
elegant way to take basename of directory in python?,"os.path.dirname(os.path.join(output_dir, ''))"
playing a lot of sounds at once,pg.mixer.init()
what is the best way to capture output from a process using python?,"process = subprocess.Popen(['python', '-h'], bufsize=1)"
how to get output of exe in python script?,"p1 = subprocess.Popen(['cmd', '/C', 'date'], stdout=subprocess.PIPE)
p1.communicate()[0]"
how to sort lists within list in user defined order?,"[['*', '+', '-'], ['*', '*', '-'], ['/', '+', '-']]"
how to print backslash with python?,print('\\')
why do i need lambda to apply functions to a pandas dataframe?,df['SR'] = df['Info'].apply(foo)
get current url in python,self.request.url
can i get a lint error on implicit string joining in python?,x = 'abcde'
disable output of root logger,logging.getLogger().setLevel(logging.DEBUG)
split string `string` on whitespaces using a generator,"return (x.group(0) for x in re.finditer(""[A-Za-z']+"", string))"
python sort parallel arrays in place?,"perm = sorted(range(len(foo)), key=lambda x: foo[x])"
python sort list of lists with casting,"[['bla', '-0.2', 'blub'], ['bla', '0.1', 'blub'], ['blaa', '0.3', 'bli']]"
returning notimplemented from __eq__,raise TypeError('sth')
replace non-ascii chars from a unicode string in python,"unicodedata.normalize('NFKD', 'm\xfasica').encode('ascii', 'ignore')"
"add key ""item3"" and value ""3"" to dictionary `default_data `",default_data['item3'] = 3
how to gracefully fallback to `nan` value while reading integers from a csv with pandas?,"df = pd.read_csv('my.csv', na_values=['n/a'])"
how to prepend a path to sys.path in python?,pprint(sys.path)
python: pandas dataframe how to multiply entire column with a scalar,"df.loc[:, ('quantity')] *= -1"
how to get the length of words in a sentence?,[len(x) for x in s.split()]
flask application traceback doesn't show up in server log,app.debug = true
how to get the value of a variable given its name in a string?,globals()['a']
is there a numpy function to return the first index of something in an array?,array[itemindex[0][0]][itemindex[1][0]]
remove the last element in list `a`,del a[(-1)]
the pythonic way to grow a list of lists,uniques = collections.defaultdict(set)
how do i convert a list of ascii values to a string in python?,""""""""""""".join(map(chr, L))"
how can i open an excel file in python?,"['Sheet1', 'Sheet2', 'Sheet3']"
how to resample a dataframe with different functions applied to each column?,"frame.resample('1H', how={'radiation': np.sum, 'tamb': np.mean})"
looping over a list of objects within a django template,entries_list = Recipes.objects.order_by('-id')[0:10]
sum each value in a list `l` of tuples,"map(sum, zip(*l))"
finding the index of a numpy array in a list,"next((i for i, val in enumerate(lst) if np.all(val == array)), -1)"
how to repeat pandas data frame?,"pd.concat([x] * 5, ignore_index=True)"
2d array of objects in python,nodes = [[Node() for j in range(cols)] for i in range(rows)]
using python to write specific lines from one file to another file,f.write('foo')
how do you edit cells in a sparse matrix using scipy?,"sparse.coo_matrix(([6], ([5], [7])), shape=(10, 10))"
google app engine/python - change logging formatting,logging.getLogger().handlers[0].setFormatter(fr)
how to get a list which is a value of a dictionary by a value from the list?,"reverse_d = {value: key for key, values in list(d.items()) for value in values}"
run a python script with arguments,"mrsync.sync('/tmp/targets.list', '/tmp/sourcedata', '/tmp/targetdata')"
what's the best way to generate random strings of a specific length in python?,print(''.join(choice(ascii_uppercase) for i in range(12)))
in tkinter is there any way to make a widget not visible? ,root.mainloop()
background color for tk in python,root.configure(background='black')
pandas: slice a multiindex by range of secondary index,"s.loc[slice('a', 'b'), slice(2, 10)]"
creating list from file in python,your_list = [int(i) for i in f.read().split()]
returning the product of a list,"from functools import reduce
reduce(lambda x, y: x * y, list, 1)"
combining two sorted lists in python,sorted(l1 + l2)
open document with default application in python,os.system('start ' + filename)
comparing multiple dictionaries in python,return dict([k_v for k_v in list(d1.items()) if k_v[0] in d2 and d2[k_v[0]] == k_v[1]])
python sorting - a list of objects,somelist.sort(key=lambda x: x.resultType)
"on windows, how to convert a timestamps before 1970 into something manageable?","datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=-2082816000)"
getting the nth element using beautifulsoup,rows = soup.findAll('tr')[4::5]
convert integer to binary,"""""""{:b}"""""".format(some_int)"
unpack the arguments out of list `params` to function `some_func`,some_func(*params)
static properties in python,MyClass.__dict__
accessing the default argument values in python,test.__defaults__
python regex to separate strings which ends with numbers in parenthesis,print([[j.split('(')[0] for j in i.split()] for i in L1])
why am i receiving a string from the socket until the \n newline escape sequence in python?,socket.close()
drop a single subcolumn 'a' in column 'col1' from a dataframe `df`,"df.drop(('col1', 'a'), axis=1)"
how to run flask with gunicorn in multithreaded mode,app.run()
grouping dataframes in pandas?,"df.groupby(['A', 'B'])['C'].unique()"
how to select columns from groupby object in pandas?,"df.groupby(['a', 'name']).median().index.get_level_values('name')"
string formatting for hex colors in python,print('{0:06x}'.format(123))
how to use logging with python's fileconfig and configure the logfile filename,"logging.fileConfig(loginipath, defaults={'logfilename': '/var/log/mylog.log'})"
inserting values into specific locations in a list in python,"[(mylist[i:] + [newelement] + mylist[:i]) for i in range(len(mylist), -1, -1)]"
getting the correct timezone offset in python using local timezone,dt = pytz.utc.localize(dt)
pandas cumulative sum of partial elements with groupby,df['*PtsPerOrder*'] = df.groupby('OrderNum')['PtsPerLot'].transform(sum)
update a user's name as `bob marley` having id `123` in sqlalchemy,session.query(User).filter_by(id=123).update({'name': 'Bob Marley'})
python string format() with dict with integer keys,'hello there %(5)s' % {'5': 'you'}
how to get different colored lines for different plots in a single figure?,plt.show()
python decimals format,"print('{0} --> {1}'.format(num, result))"
how to plot with x-axis at the top of the figure?,ax.xaxis.set_ticks_position('top')
how do you get output parameters from a stored procedure in python?,"cur.callproc('my_stored_proc', (first_param, second_param, an_out_param))"
flattening a list of numpy arrays?,np.concatenate(input_list).ravel().tolist()
how to calculate centroid in python,"data[:, -3:]"
how to find out if there is data to be read from stdin on windows in python?,os.isatty(sys.stdin.fileno())
is there a matplotlib equivalent of matlab's datacursormode?,plt.show()
why i can't convert a list of str to a list of floats?,C1 = [float(i) for i in C if i]
capitalizing non-ascii words in python,print('\xc3\xa9'.decode('cp1252').capitalize().encode('cp1252'))