text
stringlengths
4
1.08k
how to calculate percentage of sparsity for a numpy array/matrix?,np.prod(a.shape)
using variables in python regular expression,re.compile('{}-\\d*'.format(user))
handle the `urlfetch_errors ` exception for imaplib request to url `url`,"urlfetch.fetch(url, deadline=10 * 60)"
input a tuple of integers from user,"tuple(int(x.strip()) for x in input().split(','))"
most pythonic way to provide global configuration variables in config.py?,config['mysql']['tables']['users']
matplotlib plot datetime in pandas dataframe,df['date_int'] = df.date.astype(np.int64)
how to use http method delete on google app engine?,self.response.out.write('Permission denied')
number formatting in python,"print('%gx\xc2\xb3 + %gx\xc2\xb2 + %gx + %g = 0' % (a, b, c, d))"
"round off entries in dataframe `df` column `alabama_exp` to two decimal places, and entries in column `credit_exp` to three decimal places","df.round({'Alabama_exp': 2, 'Credit_exp': 3})"
convert bytes to a python string,"""""""hello"""""".decode(encoding)"
find the index of the second occurrence of the substring `bar` in string `foo bar bar bar`,"""""""foo bar bar bar"""""".replace('bar', 'XXX', 1).find('bar')"
titlecasing a string with exceptions,"""""""There is a way"""""".title()"
is there a list of all ascii characters in python's standard library?,ASCII = ''.join(chr(x) for x in range(128))
count number of events in an array python,"1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0"
elementwise product of 3d arrays `a` and `b`,"np.einsum('ijk,ikl->ijl', A, B)"
confused about running scrapy from within a python script,log.start()
how to download a file via ftp with python ftplib,"ftp.retrbinary('RETR %s' % filename, file.write)"
splitting a dictionary in python into keys and values,"keys, values = zip(*list(dictionary.items()))"
python zip() function for a matrix,zip(*A)
delete all rows in a numpy array `a` where any value in a row is zero `0`,"a[np.all(a != 0, axis=1)]"
how do i convert a django queryset into list of dicts?,"Blog.objects.values('id', 'name')"
"store integer 3, 4, 1 and 2 in a list","[3, 4, 1, 2]"
convert base-2 binary number string to int,"int('11111111', 2)"
reshape pandas dataframe from rows to columns,"pd.concat([df2[df2.Name == 'Jane'].T, df2[df2.Name == 'Joe'].T])"
how to unnest a nested list?,"from functools import reduce
reduce(lambda x, y: x + y, A, [])"
how to use raw_input() with while-loop,i = int(input('>> '))
how to find all occurrences of a pattern and their indices in python,"[x.span() for x in re.finditer('foo', 'foo foo foo foo')]"
how to filter a dictionary according to an arbitrary condition function?,"{k: v for k, v in points.items() if v[0] < 5 and v[1] < 5}"
how to get the seconds since epoch from the time + date output of gmtime() in python?,calendar.timegm(time.gmtime())
how to get a list of matchable characters from a regex class,"print(re.findall(pattern, x))"
defining the midpoint of a colormap in matplotlib,ax.set_yticks([])
applying a function to values in dict,"d2 = {k: f(v) for k, v in list(d1.items())}"
convert ndarray with shape 3x3 to array,"np.zeros((3, 3)).ravel()"
how find values in an array that meet two conditions using python,numpy.nonzero((a > 3) & (a < 8))
"on the google app engine, how do i change the default logging level of the dev_appserver.py?",logging.getLogger().handlers[0].setLevel(logging.DEBUG)
convert list of strings to dictionary,d[i[0]] = int(i[1])
sum the length of all strings in a list `strings`,length = sum(len(s) for s in strings)
python: how to find the slope of a graph drawn using matplotlib?,plt.show()
how do i find out my python path using python?,print(sys.path)
convert a 1d array to a 2d array in numpy,"B = np.reshape(A, (-1, 2))"
django: how do i get the model a model inherits from?,StreetCat._meta.get_parent_list()
implementing google's diffmatchpatch api for python 2/3,"[(-1, 'stackoverflow'), (1, 'so'), (0, ' is '), (-1, 'very'), (0, ' cool')]"
python - start a function at given time,"threading.Timer(delay, self.update).start()"
is there a function in python which generates all the strings of length n over a given alphabet?,"[''.join(i) for i in itertools.product('ab', repeat=4)]"
pythonic way to associate list elements with their indices,"d = dict((y, x) for x, y in enumerate(t))"
python: how do i make a subclass from a superclass?,"super(MySubClassBetter, self).__init__()"
multiply the columns of sparse matrix `m` by array `a` then multiply the rows of the resulting matrix by array `a`,"numpy.dot(numpy.dot(a, m), a)"
move last item of array `a` to the first position,a[-1:] + a[:-1]
add legend to seaborn point plot,plt.show()
replace first occurrence only of a string?,"text = text.replace('very', 'not very', 1)"
how to iterate through sentence of string in python?,""""""" """""".join(PorterStemmer().stem_word(word) for word in text.split(' '))"
confusing with the usage of regex in python,"re.findall('([a-z]*)', 'f233op')"
start a new thread for `myfunction` with parameters 'mystringhere' and 1,"thread.start_new_thread(myfunction, ('MyStringHere', 1))"
__builtin__ module in python,print(dir(sys.modules['__builtin__']))
python: how to convert a string containing hex bytes to a hex string,s.decode('hex')
extract row with maximum value in a group pandas dataframe,"df.groupby('Mt', as_index=False).first()"
delete column 'column_name' from dataframe `df`,"df = df.drop('column_name', 1)"
"extracting a region from an image using slicing in python, opencv",cv2.destroyAllWindows()
import local function from a module housed in another directory with relative imports in jupyter notebook using python3,sys.path.append(module_path)
how to format a list of arguments `my_args` into a string,"'Hello %s' % ', '.join(my_args)"
how to let a python thread finish gracefully,time.sleep(10)
passing sqlite variables in python,"cursor.execute(query, data)"
remove anything following first character that is not a letter in a string in python,"re.split('[^A-Za-z ]| ', 'Are you 9 years old?')[0].strip()"
python 2.7 getting user input and manipulating as string without quotations,testVar = input('Ask user for something.')
3 different issues with ttk treeviews in python,"ttk.Style().configure('.', relief='flat', borderwidth=0)"
check if values in a set are in a numpy array in python,"numpy.where(mask, 1, numpy.where(numpy_array == 0, 0, 2))"
round 1123.456789 to be an integer,"print(round(1123.456789, -1))"
using python to add a list of files into a zip file,"ZipFile.write(a, compress_type=zipfile.ZIP_DEFLATED)"
python: how to sort a dictionary by key,"sorted(iter(result.items()), key=lambda key_value: key_value[0])"
ignore an element while building list in python,[r for r in (f(char) for char in string) if r is not None]
convert string into datetime.time object,"datetime.datetime.strptime('03:55', '%H:%M').time()"
how to get a function name as a string in python?,my_function.__name__
how can i speed up fetching pages with urllib2 in python?,return urllib.request.urlopen(url).read()
3d plotting with python,plt.show()
how to scroll text in python/curses subwindow?,stdscr.getch()
how to change file access permissions in linux?,"os.chmod(path, mode)"
sort dataframe `df` based on column 'a' in ascending and column 'b' in descending,"df.sort_values(['a', 'b'], ascending=[True, False])"
beautifulsoup can't find href in file using regular expression,"print(soup.find('a', href=re.compile('.*follow\\?page.*')))"
"build a dictionary containing the conversion of each list in list `[['two', 2], ['one', 1]]` to a key/value pair as its items","dict([['two', 2], ['one', 1]])"
how can i make tabs in pygtk closable?,gtk.main()
get name of primary field `name` of django model `custompk`,CustomPK._meta.pk.name
how to get the n next values of a generator in a list (python),list(next(it) for _ in range(n))
conditional replacement of multiple columns based on column values in pandas dataframe,"df[df.loc[:] == ''] = df.copy().shift(2, axis=1)"
how to convert a python numpy array to an rgb image with opencv 2.4?,"cv2.imshow('image', img)"
python tkinter - resize widgets evenly in a window,"self.grid_rowconfigure(1, weight=1)"
python: a4 size for a plot,"figure(figsize=(11.69, 8.27))"
how to check if type of a variable is string?,"isinstance(s, str)"
customize the time format in python logging,formatter = logging.Formatter('%(asctime)s;%(levelname)s;%(message)s')
how to do bitwise exclusive or of two strings in python?,"l = [(ord(a) ^ ord(b)) for a, b in zip(s1, s2)]"
django get first 10 records of model `user` ordered by criteria 'age' of model 'pet',User.objects.order_by('-pet__age')[:10]
sort a list by multiple attributes?,"s.sort(key=operator.itemgetter(1, 2))"
check if string `foo` is utf-8 encoded,foo.decode('utf8').encode('utf8')
check if character '-' exists in a dataframe `df` cell 'a',df['a'].str.contains('-')
remove trailing newline in string 'test string \n\n','test string \n\n'.rstrip('\n')
how to get unique values with respective occurance count from a list in python?,"[(g[0], len(list(g[1]))) for g in itertools.groupby(['a', 'a', 'b', 'b', 'b'])]"
how to make good reproducible pandas examples,df['date'] = pd.to_datetime(df['date'])
how do i insert a jpeg image into a python tkinter window?,window.geometry('450x1000+200+0')
how to obtain all unique combinations of values of particular columns,"df.drop_duplicates(subset=['Col2', 'Col3'])"
python convert list to dictionary,"dict(zip(it, it))"