text
stringlengths
4
1.08k
How do I update an instance of a Django Model with request.POST if POST is a nested array?,form.save()
google app engine python download file,"self.response.out.write(','.join(['a', 'cool', 'test']))"
Python: how to change (last) element of tuple?,"b = a[:-1] + (a[-1] * 2,)"
Python - finding the longest sequence with findall,"sorted(re.findall('g+', 'fggfggggfggfg'), key=len, reverse=True)"
How do I use xml namespaces with find/findall in lxml?,"root.xpath('.//table:table', namespaces=root.nsmap)"
How to set the working directory for a Fabric task?,run('ls')
float64 with pandas to_csv,"df.to_csv('pandasfile.csv', float_format='%.3f')"
Python Pandas - Using to_sql to write large data frames in chunks,"df.to_sql('table', engine, chunksize=20000)"
Inserting JSON into MySQL using Python,"db.execute('INSERT INTO json_col VALUES %s', json_value)"
Run bash script with python - TypeError: bufsize must be an integer,"call(['tar', 'xvf', path])"
Add legend to scatter plot,plt.show()
Python: for loop in index assignment,a = [str(wi) for wi in wordids]
How to configure Logging in Python,logging.info('Doing something')
How to find subimage using the PIL library?,"print(np.unravel_index(result.argmax(), result.shape))"
Python Sockets: Enabling Promiscuous Mode in Linux,"fcntl.ioctl(s.fileno(), SIOCSIFFLAGS, ifr)"
How do I clear all variables in the middle of a Python script?,dir()
"How to maintain a strict alternating pattern of item ""types"" in a list?","re.sub('(AA+B+)|(ABB+)', '', data)"
Twitter Streaming API with Tweepy rejects oauth,"auth.set_access_token(access_token, access_token_secret)"
Django search multiple filters,u = User.objects.filter(userjob__job__name='a').filter(userjob__job__name='c')
How do I get the ID of an object after persisting it in PyMongo?,collection.remove({'_id': ObjectId('4c2fea1d289c7d837e000000')})
"Pyramid on App Engine gets ""InvalidResponseError: header values must be str, got 'unicode'",self.redirect('/home.view')
How to add group labels for bar charts in matplotlib?,fig.savefig('label_group_bar_example.png')
Python precision in string formatting with float numbers,"format(38.2551994324, '.32f')"
Convert Average of Python List Values to Another List,"zip(*[[5, 7], [6, 9], [7, 4]])"
Compare two columns using pandas,df2 = df.astype(float)
Python / Remove special character from string,"print(re.sub('[^\\w.]', '', string))"
Save image created via PIL to django model,img.save()
Tkinter adding line number to text widget,root.mainloop()
extract last two fields from split,s.split(':')[-2:]
Convert list of strings to dictionary,d[i[0]] = int(i[1])
How do I step through/debug a python web application?,pdb.set_trace()
How to add a constant column in a Spark DataFrame?,"df.withColumn('new_column', lit(10))"
What does a colon and comma stand in a python list?,"foo[:, (1)]"
How to get the sum of timedelta in Python?,"datetime.combine(date.today(), time()) + timedelta(hours=2)"
How can I generate a list of consecutive numbers?,"[0, 1, 2, 3, 4, 5, 6, 7, 8]"
Perl like regex in Python,"match = re.search('(.*?):([^-]*)-(.*)', line)"
How to create a self resizing grid of buttons in tkinter?,root.mainloop()
Python : How to avoid numpy RuntimeWarning in function definition?,"a = np.array(a, dtype=np.float128)"
Running compiled python (py2exe) as administrator in Vista,"windows = [{'script': 'admin.py', 'uac_info': 'requireAdministrator'}]"
Use regular expressions to replace overlapping subpatterns,"re.sub('([a-zA-Z0-9])\\s+(?=[a-zA-Z0-9])', '\\1*', '3 /a 5! b')"
Python Matplotlib: plot with 2-dimensional arguments : how to specify options?,"plot(x[0], y[0], 'red', x[1], y[1], 'black')"
Simple way of creating a 2D array with random numbers (Python),[[random.random() for i in range(N)] for j in range(N)]
is there a binary OR operator in python that works on arrays?,"c = [(x | y) for x, y in zip(a, b)]"
Python lists with scandinavic letters,"['Hello', 'w\xc3\xb6rld']"
Generate a sequence of numbers in Python,""""""","""""".join(map(str, sorted(list(range(1, 100, 4))) + list(range(2, 100, 4))))"
Is there a way to access the context from everywhere in Django?,return {'ip_address': request.META['REMOTE_ADDR']}
How do I transform a multi-level list into a list of strings in Python?,"from functools import reduce
[reduce(lambda x, y: x + y, i) for i in a]"
"""Missing redirect_uri parameter"" response from Facebook with Python/Django","conn.request('GET', '/oauth/access_token', params)"
How do you plot a vertical line on a time series plot in Pandas?,"ax.axvline(pd.to_datetime('2015-11-01'), color='r', linestyle='--', lw=2)"
Appending column totals to a Pandas DataFrame,df['Total'] = df.sum(axis=1)
How to keep a Python script output window open?,input()
in python: iterate over each string in a list,print(list(enumerate(words)))
How to pause and wait for command input in a python script,pdb.set_trace()
pyodbc insert into sql,cnxn.commit()
"How to get files in a directory, including all subdirectories","print(os.path.join(dirpath, filename))"
Passing SQLite variables in Python,"cursor.execute(query, data)"
Close a tkinter window?,root.quit()
Encoding an image file with base64,encoded_string = base64.b64encode(image_file.read())
"In Python, is there a concise way to use a list comprehension with multiple iterators?","[(i, j) for i in range(10) for j in range(i)]"
"Python Selenium Safari, disable logging",browser = webdriver.Safari(quiet=True)
Reading a CSV into pandas where one column is a json string,df.join(df['stats'].apply(json.loads).apply(pd.Series))
Select value from list of tuples where condition,results = [t[1] for t in mylist if t[0] == 10]
Download a remote image and save it to a Django model,image = models.ImageField(upload_to='images')
python pandas convert dataframe to dictionary with multiple values,"{k: list(v) for k, v in df.groupby('Address')['ID']}"
"Printing correct time using timezones, Python",print(aware.astimezone(Pacific).strftime('%a %b %d %X %z'))
How can I get the current contents of an element in webdriver,driver.quit()
Is there a list of all ASCII characters in python's standard library?,ASCII = ''.join(chr(x) for x in range(128))
Python: Write a list of tuples to a file,fp.write('\n'.join('%s %s' % x for x in mylist))
Check whether a path is valid in Python without creating a file at the path's target,"open(filename, 'r')"
Comparing two dictionaries in Python,"zip(iter(x.items()), iter(y.items()))"
Returning the highest 6 names in a List of tuple in Python,"heapq.nlargest(6, your_list, key=itemgetter(1))"
Python regex to get everything until the first dot in a string,find = re.compile('^(.*?)\\..*')
datetime to string with series in python pandas,dates.dt.strftime('%Y-%m-%d')
"Given a list of variable names in Python, how do I a create a dictionary with the variable names as keys (to the variables' values)?","dict((name, locals()[name]) for name in list_of_variable_names)"
matplotlib (mplot3d) - how to increase the size of an axis (stretch) in a 3D Plot?,"ax.plot(x, y, z, label='parametric curve')"
Efficient way to create strings from a list,"['_'.join(k + v for k, v in zip(d, v)) for v in product(*list(d.values()))]"
Pandas Histogram of Filtered Dataframe,df[df.TYPE == 'SU4'].GVW.hist(bins=50)
find position of a substring in a string,"match = re.search('[^a-zA-Z](is)[^a-zA-Z]', mystr)"
Change the color of the plot depending on the density (stored in an array) in line plot in matplotlib,plt.show()
How do convert a pandas/dataframe to XML?,"print('\n'.join(df.apply(func, axis=1)))"
How to calculate relative path between 2 directory path?,"os.path.relpath(subdir2, subdir1)"
Select rows in Pandas which does not contain a specific character,df['str_name'].str.contains('c')
How to create a number of empty nested lists in python,"[[], [], [], [], [], [], [], [], [], []]"
clicking on a link via selenium in python,link = driver.find_element_by_link_text('Details')
Is there a way to poll a file handle returned from subprocess.Popen?,sys.stdout.flush()
how to use groupby to avoid loop in python,df.ix[idx]
How can Python regex ignore case inside a part of a pattern but not the entire expression?,"re.match('[Ff][Oo]{2}bar', 'Foobar')"
what would be the python code to add time to a specific timestamp?,"k.strftime('%H:%M:%S,%f ')"
Find object by its member inside a List in python,[x for x in myList if x.age == 30]
How to select rows start with some str in pandas?,"df.query('col.str[0] not list(""tc"")')"
How do I access the request object or any other variable in a form's clean() method?,"myform = MyForm(request.POST, request=request)"
How to include a quote in a raw Python string?,"""""""what""ever"""""""
How to include a quote in a raw Python string?,"""""""what""ev'er"""""""
How to check for a key in a defaultdict without updating the dictionary (Python)?,"dct.get(key, 'ham')"
Python update object from dictionary,"setattr(self, key, value)"
How can I get an email message's text content using python?,msg.get_payload()
How to get the size of a string in Python?,print(len('\xd0\xb9\xd1\x86\xd1\x8b'.decode('utf8')))
Displaying a list of items vertically in a table instead of horizonally,[l[i::5] for i in range(5)]
Iterate over a dictionary by comprehension and get a dictionary,"dict((k, mimes[k]) for k in mimes if mimes[k] == 'image/tiff')"