text
stringlengths
4
1.08k
how do i connect to a mysql database in python?,db.close()
django filter with list of values,"Blog.objects.filter(pk__in=[1, 4, 7])"
how do i remove all punctuation that follows a string?,"""""""words!?.,;:"""""".rstrip('?:!.,;')"
the truth value of an array with more than one element is ambigous when trying to index an array,"c[np.logical_and(a, b)]"
animating 3d scatterplot in matplotlib,plt.show()
parsing webpage 'http://www.google.com/' using beautifulsoup,"page = urllib.request.urlopen('http://www.google.com/')
soup = BeautifulSoup(page)"
sort a sublist of elements in a list leaving the rest in place,"['X', 'B', 'B1', 'B2', 'B11', 'B21', 'B22', 'C', 'Q1', 'C11', 'C2']"
"combining two lists and removing duplicates, without removing duplicates in original list",print(first_list + list(set(second_list) - set(first_list)))
in python how can i declare a dynamic array,lst.append('a')
pythonic way of removing reversed duplicates in list,data = {tuple(sorted(item)) for item in lst}
correct way to edit dictionary value python,"my_dict.setdefault('foo', {})['bar'] = some_var"
how to store python dictionary in to mysql db through python,cursor.commit()
how to unpack a list?,"print(tuple(chain(['a', 'b', 'c'], 'd', 'e')))"
make a function `f` that calculates the sum of two integer variables `x` and `y`,"f = lambda x, y: x + y"
creating a list of objects in python,instancelist = [MyClass() for i in range(29)]
selecting positive certain values from a 2d array in python,"[[0.0, 3], [0.1, 1]]"
replace a substring selectively inside a string,"re.sub('\\bdelhi\\b(?=(?:""[^""]*""|[^""])*$)', '', a)"
setting the limits on a colorbar in matplotlib,plt.show()
find indexes of all occurrences of a substring `tt` in a string `ttt`,"[m.start() for m in re.finditer('(?=tt)', 'ttt')]"
how can i color python logging output?,"logging.Logger.__init__(self, name, logging.DEBUG)"
extract dictionary value from column in data frame,feature3 = [d.get('Feature3') for d in df.dic]
print string as hex literal python,"""""""ABC"""""".encode('hex')"
django - taking values from post request,"request.POST.get('title', '')"
python summing elements of one dict if the have a similar key(tuple),"{k: sum(v) for k, v in list(trimmed.items())}"
using savepoints in python sqlite3,conn.execute('savepoint spTest;')
python - how to extract the last x elements from a list,new_list = my_list[-10:]
python(pandas): removing duplicates based on two columns keeping row with max value in another column,"df.groupby(['A', 'B']).max()['C']"
how do i combine two columns within a dataframe in pandas?,df['c'] = df['b'].fillna(df['a'])
sorting dictionary keys based on their values,"sorted(d, key=lambda k: d[k][1])"
comparing elements between elements in two lists of tuples,"[x[0] for x, y in zip(l1, l2) if x[0] == y[0]]"
python repeat string,print('[{0!r}] ({0:_^15})'.format(s[:5]))
updating csv with data from a csv with different formatting,"cdf1.to_csv('temp.csv', index=False)"
format float `3.5e+20` to `$3.5 \\times 10^{20}$` and set as title of matplotlib plot `ax`,"ax.set_title('$%s \\times 10^{%s}$' % ('3.5', '+20'))"
call a function with argument list in python,"func(*args, **kwargs)"
set multi index of an existing data frame in pandas,"df = df.set_index(['Company', 'date'], inplace=True)"
how to to filter dict to select only keys greater than a value?,"{k: v for k, v in list(mydict.items()) if k >= 6}"
python string replacement,"re.sub('\\bugh\\b', 'disappointed', 'laughing ugh')"
python: get int value from a char string,"int('AEAE', 16)"
how to print a list more nicely?,"zip([1, 2, 3], ['a', 'b', 'c'], ['x', 'y', 'z'])"
how do you pass arguments from one function to another?,"some_other_function(*args, **kwargs)"
python pandas: plot histogram of dates?,df.date = df.date.astype('datetime64')
printing list in python properly,"print('[%s]' % ', '.join(map(str, mylist)))"
row-to-column transposition in python,"[(1, 4, 7), (2, 5, 8), (3, 6, 9)]"
how can i plot hysteresis in matplotlib?,"ax.scartter(XS, YS, ZS)"
insert directory './path/to/your/modules/' to current directory,"sys.path.insert(0, './path/to/your/modules/')"
getting one value from a python tuple,i = 5 + Tup()[0]
how to set cookie in python mechanize,"br.addheaders = [('Cookie', 'cookiename=cookie value')]"
how to plot a rectangle on a datetime axis using matplotlib?,plt.show()
how to decode a 'url-encoded' string in python,urllib.parse.unquote(urllib.parse.unquote('FireShot3%2B%25282%2529.png'))
how can i find all subclasses of a class given its name?,print([cls.__name__ for cls in vars()['Foo'].__subclasses__()])
progress line in matplotlib graphs,plt.show()
how to label a line in python?,plt.show()
"calling an external command ""echo hello world""","print(subprocess.Popen('echo Hello World', shell=True, stdout=subprocess.PIPE).stdout.read())"
how can i set proxy with authentication in selenium chrome web driver using python,driver.get('http://www.google.com.br')
combine multiple text files into one text file using python,outfile.write(infile.read())
parse_dates in pandas,"df['date'] = pd.to_datetime(df['date'], format='%d%b%Y')"
pandas dropna - store dropped rows,"df.dropna(subset=['col2', 'col3'])"
how to terminate process from python using pid?,p.terminate()
pull tag value using beautifulsoup,"print(soup.find('span', {'class': 'thisClass'})['title'])"
get index of the first biggest element in list `a`,a.index(max(a))
how to read file with space separated values,"pd.read_csv('whitespace.csv', header=None, delimiter='\\s+')"
how to use pgdb.executemany?,pgdb.paramstyle
"build a dict of key:value pairs from a string representation of a dict, `{'muffin' : 'lolz', 'foo' : 'kitty'}`","ast.literal_eval(""{'muffin' : 'lolz', 'foo' : 'kitty'}"")"
is it possible to get widget settings in tkinter?,root.mainloop()
how to overplot a line on a scatter plot in python?,"plt.plot(x, m * x + b, '-')"
python creating a smaller sub-array from a larger 2d numpy array?,"data[:, ([1, 2, 4, 5, 7, 8])]"
how to assign a string value to an array in numpy?,"CoverageACol = numpy.array([['a', 'b'], ['c', 'd']], dtype=numpy.dtype('a16'))"
python numpy 2d array indexing,b[a].shape
how do i make a pop up in tkinter when a button is clicked?,app.mainloop()
how do i query objects of all children of a node with django mptt?,Student.objects.filter(studentgroup__level__pk=1)
python: assign each element of a list to a separate variable,"a, b, c = [1, 2, 3]"
matplotlib: how to force integer tick labels?,ax.xaxis.set_major_locator(MaxNLocator(integer=True))
how to convert a pandas dataframe subset of columns and rows into a numpy array?,"df[df.c > 0.5][['b', 'e']].values"
map two lists into a dictionary in python,"dict([(k, v) for k, v in zip(keys, values)])"
regex: how to match words without consecutive vowels?,"[w for w in open('file.txt') if not re.search('([aeiou])\\1', w)]"
how to find the target file's full(absolute path) of the symbolic link or soft link in python,os.path.realpath(path)
lack of rollback within testcase causes unique contraint violation in multi-db django app,multi_db = True
pymongo sorting by date,"db.posts.find().sort('date', -1)"
converting datetime.date to utc timestamp in python,"timestamp = (dt - datetime(1970, 1, 1)).total_seconds()"
jinja join elements of array `tags` with space string ' ',{{tags | join(' ')}}
how to use regular expression in lxml xpath?,"doc.xpath(""//a[starts-with(text(),'some text')]"")"
google app engine - request class query_string,self.request.get_all()
"split string ""this is a string"" into words that do not contain whitespaces","""""""This is a string"""""".split()"
generating all unique pair permutations,"list(permutations(list(range(9)), 2))"
convert sets to frozensets as values of a dictionary,"d = {k: frozenset(v) for k, v in list(d.items())}"
how to use python pandas to get intersection of sets from a csv file,csv_pd.query('setA==1 & setB==0 & setC==0').groupby('D').count()
pandas dataframe groupby and get nth row,df.groupby('ID').apply(lambda t: t.iloc[1])
python regular expression matching a multiline block of text,"re.compile('^(.+)(?:\\n|\\r\\n?)((?:(?:\\n|\\r\\n?).+)+)', re.MULTILINE)"
io error while storing data in pickle,"output = open('/home/user/test/wsservice/data.pkl', 'wb')"
how to generate random numbers that are different?,"random.sample(range(1, 50), 6)"
how do i print the content of a .txt file in python?,file_contents = f.read()
split dataframe `df` where the value of column `a` is equal to 'b',df.groupby((df.a == 'B').shift(1).fillna(0).cumsum())
matplotlib: drawing lines between points ignoring missing data,plt.show()
"slicing of a numpy 2d array, or how do i extract an mxm submatrix from an nxn array (n>m)?","x[[[1], [3]], [1, 3]]"
replacing few values in a pandas dataframe column with another value,"df['BrandName'] = df['BrandName'].replace(['ABC', 'AB'], 'A')"
sort a list by the number of occurrences of the elements in the list,"sorted(A, key=key_function)"
get a random boolean in python?,bool(random.getrandbits(1))
best way to remove elements from a list,[item for item in my_list if some_condition()]
joining pairs of elements of a list - python,"[(x[i] + x[i + 1]) for i in range(0, len(x), 2)]"