text
stringlengths
4
1.08k
how can i split and parse a string in python?,"""""""2.7.0_bf4fda703454"""""".split('_')"
python - putting list items in a queue,"map(self.queryQ.put, self.getQueries())"
how to convert unicode numbers to ints?,print(to_float('\xc2\xbe'))
how to fill a polygon with a custom hatch in matplotlib?,plt.show()
python: print a generator expression?,[x for x in foo]
private members in python,"['_Test__private_symbol', '__doc__', '__module__', 'normal_symbol']"
python: for loop in index assignment,[str(wi) for wi in wordids]
finding words after keyword in python,"re.search('name (\\w+)', s)"
add a colorbar to plot `plt` using image `im` on axes `ax`,"plt.colorbar(im, ax=ax)"
finding groups of increasing numbers in a list,"[(1, 2, 3), (1, 2, 3)]"
decode url `url` with utf8 and print it,print(urllib.parse.unquote(url).decode('utf8'))
more elegant way to implement regexp-like quantifiers,"['x', ' ', 'y', None, ' ', 'z']"
how do i merge two lists into a single list?,"[j for i in zip(a, b) for j in i]"
add sum of values of two lists into new list,[sum(x) for x in zip(*lists_of_lists)]
how to use different formatters with the same logging handler in python,logging.getLogger('base.baz').error('Log from baz')
multiple linear regression with python,import pandas as pd
"getting every file in a directory, python",a = [name for name in os.listdir('.') if name.endswith('.txt')]
selecting specific column in each row from array,A[0][0:4]
split column 'ab' in dataframe `df` into two columns by first whitespace ' ',"df['AB'].str.split(' ', 1, expand=True)"
using python to convert integer to binary,bin(0)
datetime.datetime.now() + 1,"datetime.datetime.now() + datetime.timedelta(days=1, hours=3)"
extract a part of values from a column,df.Results.str.extract('passed ([0-9]+)').fillna(0)
sort numpy float array `a` column by column,"A = np.array(sorted(A, key=tuple))"
how to make curvilinear plots in matplotlib,plt.axis('off')
"converting an array of integers to a ""vector""","mapping = np.array([[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0]])"
concatenating values in list `l` to a string,"makeitastring = ''.join(map(str, L))"
dumping subprcess output in a file in append mode,fh1.seek(2)
beautifulsoup find tag 'div' with styling 'width=300px;' in html string `soup`,"soup.findAll('div', style='width=300px;')"
how to convert a string to its base-10 representation?,"int(''.join([hex(ord(x))[2:] for x in 'YZ']), 16)"
replace white spaces in dataframe `df` with '_',"df.replace(' ', '_', regex=True)"
django - how to sort queryset by number of character in a field,MyModel.objects.extra(select={'length': 'Length(name)'}).order_by('length')
call perl script from python,"subprocess.call(['/usr/bin/perl', './uireplace.pl', var])"
how to check if two keys in dict hold the same value,len(list(dictionary.values())) == len(set(dictionary.values()))
sum a list of numbers in python,sum(list_of_nums)
python: how to get multiple variables from a url in flask?,"{'a': 'hello', 'b': 'world'}"
indexing one array by another in numpy,"A[np.arange(A.shape[0])[:, (None)], B]"
join last element in list,""""""" & """""".join(['_'.join(inp[:2]), '_'.join(inp[2:])])"
get a list of items form nested list `li` where third element of each item contains string 'ar',[x for x in li if 'ar' in x[2]]
how to create ternary contour plot in python?,plt.show()
how to group pandas dataframe entries by date in a non-unique column,data.groupby(lambda x: data['date'][x].year)
how to show the whole image when using opencv warpperspective,cv2.waitKey()
python twisted reactor undefined variable,reactor.run()
create a symlink directory `d:\\testdirlink` for directory `d:\\testdir` with unicode support using ctypes library,"kdll.CreateSymbolicLinkW('D:\\testdirLink', 'D:\\testdir', 1)"
how to sort a dictionary having keys as a string of numbers in python,"print(sorted(list(a.items()), key=lambda t: get_key(t[0])))"
slice a string after a certain phrase?,"s.split('fdasfdsafdsa', 1)[0]"
mitm proxy over ssl hangs on wrap_socket with client,connection.send('HTTP/1.0 200 OK')
pandas (python): how to add column to dataframe for index?,df['index_col'] = df.index
python: how do i format a date in jinja2?,{{car.date_of_manufacture | datetime}}
delete the element `c` from list `a`,"try:
a.remove(c)
except ValueError:
pass"
selenium with ghostdriver in python on windows,browser.get('http://stackoverflow.com/')
how do i bold only part of a string in an excel cell with python,ws.Range('A1').Characters
merging data frame columns of strings into one single column in pandas,"df.apply(' '.join, axis=0)"
finding unique points in numpy array,np.random.seed(1)
interprocess communication in python,listener.close()
shuffle string in python,""""""""""""".join(random.sample(s, len(s)))"
matplotlib: multiple plots on one figure,plt.show()
python how to reduce on a list of tuple?,"sum(x * y for x, y in zip(a, b))"
syntax for creating a dictionary into another dictionary in python,print(d['dict2']['quux'])
find the row indexes of several values in a numpy array,np.where(out.ravel())[0]
how do i configure the ip address with cherrypy?,cherrypy.quickstart(HelloWorld())
get all matching patterns 'a.*?a' from a string 'a 1 a 2 a 3 a 4 a'.,"re.findall('(?=(a.*?a))', 'a 1 a 2 a 3 a 4 a')"
how to get unique list using a key word :python,list({e.id: e for e in somelist}.values())
dropping a single (sub-) column from a multiindex,"df.drop([('col1', 'a'), ('col2', 'b')], axis=1)"
"get rank of rows from highest to lowest of dataframe `df`, grouped by value in column `group`, according to value in column `value`",df.groupby('group')['value'].rank(ascending=False)
get the logical xor of two variables `str1` and `str2`,return (bool(str1) ^ bool(str2))
find all chinese characters in string `ipath`,"re.findall('[\u4e00-\u9fff]+', ipath)"
numpy: efficiently reading a large array,"a = numpy.fromfile('filename', dtype=numpy.float32)"
"regex, find first - python","re.findall('<wx\\.[^<]*<[^<]*> >', i)"
how to iterate through sentence of string in python?,""""""" """""".join(PorterStemmer().stem_word(word) for word in text.split(' '))"
"in python, how do i take the highest occurrence of something in a list, and sort it that way?","print(Counter([3, 3, 3, 4, 4, 2]).most_common())"
putting a variable inside a string (python),plot.savefig('hanning' + str(num) + '.pdf')
converting a list of strings in a numpy array in a faster way,"map(float, i.split(' ', 2)[:2])"
changing file extension in python,os.path.splitext('name.fasta')[0]
add an element in each dictionary of a list (list comprehension),"myList = [{'a': 'A'}, {'b': 'B'}, {'c': 'C', 'cc': 'CC'}]"
how can i check the data transfer on a network interface in python?,time.sleep(5)
how to find row of 2d array in 3d numpy array,"array([True, False, False, True], dtype=bool)"
how to copy files to network path or drive using python,os.system('NET USE P: /DELETE')
is there a matplotlib equivalent of matlab's datacursormode?,"plt.subplot(2, 1, 1)"
array initialization in python,"[(x + i * y) for i in range(1, 10)]"
get the average values from two numpy arrays `old_set` and `new_set`,"np.mean(np.array([old_set, new_set]), axis=0)"
"convert a list `['a:1', 'b:2', 'c:3', 'd:4']` to dictionary","dict(map(lambda s: s.split(':'), ['A:1', 'B:2', 'C:3', 'D:4']))"
redirect stdout to a file in python?,os.system('echo this also is not redirected')
updating marker style in scatter plot with matplotlib,plt.show()
sort list `mylist` of tuples by arbitrary key from list `order`,"sorted(mylist, key=lambda x: order.index(x[1]))"
print the concatenation of the digits of two numbers in python,"print('{0}{1}'.format(2, 1))"
how can i execute python code in a virtualenv from matlab,system('/path/to/my/venv/bin/python myscript.py')
clone element with beautifulsoup,"document2.body.append(document1.find('div', id_='someid').clone())"
django remove unicode in values_list,"json.dumps(definitions.objects.values_list('title', flat=True))"
parsing email with python,print(msg['Subject'])
how do i pass tuples elements to a function as arguments in python?,myfunc(*args)
python 2.7 counting number of dictionary items with given value,sum(x == chosen_value for x in list(d.values()))
python: how to loop through blocks of lines,"[('X', 'Y', '20'), ('H', 'F', '23'), ('S', 'Y', '13'), ('M', 'Z', '25')]"
multiprocessing writing to pandas dataframe,"pd.concat(d, ignore_index=True)"
decomposing html to link text and target,soup = BeautifulSoup.BeautifulSoup(urllib.request.urlopen(url).read())
"python ""extend"" for a dictionary",a.update(b)
getting a request parameter in jinja2,{{request.args.get('a')}}
open a file 'bundled-resource.jpg' in the same directory as a python script,"f = open(os.path.join(__location__, 'bundled-resource.jpg'))"