text
stringlengths
4
1.08k
How do I load session and cookies from Selenium browser to requests library in Python?,cookies = driver.get_cookies()
Clear text from textarea with selenium,driver.find_element_by_id('foo').clear()
Python - Update a value in a list of tuples,"update_in_alist([('a', 'hello'), ('b', 'world')], 'b', 'friend')"
How can I know python's path under windows?,os.path.dirname(sys.executable)
How to build and fill pandas dataframe from for loop?,pd.DataFrame(d)
Python: use regular expression to remove the white space from all lines,"re.sub('(?m)^[^\\S\\n]+', '', ' a\n b\n c\nd e')"
Selecting specific column in each row from array,"A[[0, 1], [0, 1]]"
sorting list of nested dictionaries in python,"sorted(yourdata, reverse=True)"
Pandas: Elementwise multiplication of two dataframes,"pd.DataFrame(df.values * df2.values, columns=df.columns, index=df.index)"
Compare length of three lists in python,"list(itertools.combinations(L, 2))"
Check if list item contains items from another list,[item for item in my_list if any(x in item for x in bad)]
How to iterate over list of dictionary in python?,"print(str(a['timestamp']), a['ip'], a['user'])"
How can I sum the product of two list items using for loop in python?,"list(x * y for x, y in list(zip(a, b)))"
Python - How to cut a string in Python?,"""""""foobar""""""[:4]"
Combining NumPy arrays,"b = np.concatenate((a, a), axis=0)"
Download a remote image and save it to a Django model,imgfile = models.ImageField(upload_to='images/%m/%d')
Multiple files for one argument in argparse Python 2.7,"parser.add_argument('file', nargs='*')"
"List comprehension - converting strings in one list, to integers in another",[[int(x)] for y in list_of_lists for x in y]
Creating a screenshot of a gtk.Window,gtk.main()
Regular expression substitution in Python,"line = re.sub('\\(+as .*?\\) ', '', line)"
How to use bash variables inside a Python code?,"subprocess.call(['echo $var'], shell=True)"
"in Python, how to convert list of float numbers to string with certain format?",str_list = [tuple('{0:.8e}'.format(flt) for flt in sublist) for sublist in lst]
Read a File from redirected stdin with python,result = sys.stdin.read()
How to select only specific columns from a DataFrame with MultiIndex columns?,"data.loc[:, (list(itertools.product(['one', 'two'], ['a', 'c'])))]"
google app engine python download file,self.response.headers['Content-Disposition'] = 'attachment; filename=fname.csv'
subprocess.Popen with a unicode path,"subprocess.call(['start', 'avi\xf3n.mp3'.encode('latin1')], shell=True)"
How can I determine the byte length of a utf-8 encoded string in Python?,return len(s.encode('utf-8'))
Delete digits in Python (Regex),"re.sub('$\\d+\\W+|\\b\\d+\\b|\\W+\\d+$', '', s)"
Delete digits in Python (Regex),"re.sub('\\b\\d+\\b', '', s)"
How to iterate through a list of tuples containing three pair values?,"[(1, 'B', 'A'), (2, 'C', 'B'), (3, 'C', 'A')]"
How to sort a Python dict by value,"res = list(sorted(theDict, key=theDict.__getitem__, reverse=True))"
Python: an efficient way to slice a list with a index list,c = [b[i] for i in index]
Python regex to match multiple times,"pattern = re.compile('review: (http://url.com/(\\d+)\\s?)+', re.IGNORECASE)"
Python regex to match multiple times,"pattern = re.compile('/review: (http://url.com/(\\d+)\\s?)+/', re.IGNORECASE)"
python append to array in json object,"jsobj['a']['b']['e'].append({'f': var6, 'g': var7, 'h': var8})"
Splitting a string based on a certain set of words,"re.split('_for_', 'happy_hats_for_cats')"
How to store os.system() output in a variable or a list in python,"direct_output = subprocess.check_output('ls', shell=True)"
Pandas how to apply multiple functions to dataframe,"df.groupby(lambda idx: 0).agg(['mean', 'std'])"
Extract row with maximum value in a group pandas dataframe,"df.groupby('Mt', as_index=False).first()"
Getting the nth element using BeautifulSoup,rows = soup.findAll('tr')[4::5]
Getting values from JSON using Python,"data = json.loads('{""lat"":444, ""lon"":555}')"
Python - How do I make a dictionary inside of a text file?,pickle.loads(s)
How do I connect to a MySQL Database in Python?,cur.execute('SELECT * FROM YOUR_TABLE_NAME')
Splitting a string into words and punctuation,"re.findall('\\w+|[^\\w\\s]', text, re.UNICODE)"
Python: A4 size for a plot,"figure(figsize=(11.69, 8.27))"
Python split a list into subsets based on pattern,"[list(v) for k, v in itertools.groupby(mylist, key=lambda x: x[:5])]"
Python - Get path of root project structure,os.path.dirname(sys.modules['__main__'].__file__)
Django ORM: Selecting related set,polls = Poll.objects.filter(category='foo').prefetch_related('choice_set')
TensorFlow strings: what they are and how to work with them,"x = tf.constant(['This is a string', 'This is another string'])"
How to add header row to a pandas DataFrame,"Frame = pd.DataFrame([Cov], columns=['Sequence', 'Start', 'End', 'Coverage'])"
python split string based on regular expression,str1.split()
zip lists in python,"zip([1, 2], [3, 4])"
matplotlib Legend Markers Only Once,legend(numpoints=1)
Django: Redirect to previous page after login,"return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))"
How to replace empty string with zero in comma-separated string?,"[(int(x) if x else 0) for x in data.split(',')]"
How do you get the text from an HTML 'datacell' using BeautifulSoup,''.join([s.string for s in s.findAll(text=True)])
How can I set the mouse position in a tkinter window,root.mainloop()
Sorting a list of tuples by the addition of second and third element of the tuple,"sorted(a, key=lambda x: (sum(x[1:3]), x[0]))"
How to Mask an image using Numpy/OpenCV?,cv2.waitKey(0)
Find array item in a string,any(x in string for x in search)
How can I convert a binary to a float number,"struct.unpack('d', struct.pack('Q', int(s2, 0)))[0]"
Getting the average of a certain hour on weekdays over several years in a pandas dataframe,"df1.groupby([df1.index.year, df1.index.hour]).mean()"
How to get a max string length in nested lists,"len(max(i, key=len))"
How to split a string at line breaks in python?,"print([map(solve, x.split('\t')) for x in s.rstrip().split('\r\n')])"
"How do I iterate over a Python dictionary, ordered by values?","sorted(iter(d.items()), key=lambda x: x[1])"
How to pass pointer to an array in Python for a wrapped C++ function,"AAF(10, [4, 5.5, 10], [1, 1, 2], 3)"
How to smooth matplotlib contour plot?,plt.show()
Python list of tuples to list of int,"y = map(operator.itemgetter(0), x)"
Python - How to calculate equal parts of two dictionaries?,"dict((x, set(y) & set(d1.get(x, ()))) for x, y in d2.items())"
Replace the single quote (') character from a string,"""""""didn't"""""".replace(""'"", '')"
how to split a unicode string into list,list(stru.decode('utf-8'))
Python RegEx using re.sub with multiple patterns,"word = re.sub('([aeiou]):(([aeiou][^aeiou]*){3})$', '\\1\\2', word)"
How to read Unicode input and compare Unicode strings in Python?,print(decoded.encode('utf-8'))
Is there a function in python to split a word into a list?,list('Word to Split')
How to check if all values in the columns of a numpy matrix are the same?,"np.equal.reduce([1, 0, 0, 1])"
Python Add Comma Into Number String,"print('Total cost is: ${:,.2f}'.format(TotalAmount))"
Technique to remove common words(and their plural versions) from a string,"'all', 'just', 'being', 'over', 'both', 'through', 'yourselves', 'its', 'before', 'herself', 'had', 'should', 'to', 'only', 'under', 'ours', 'has', 'do', 'them', 'his', 'very', 'they', 'not', 'during', 'now', 'him', 'nor', 'did', 'this', 'she', 'each', 'further', 'where', 'few', 'because', 'doing', 'some', 'are', 'our', 'ourselves', 'out', 'what', 'for', 'while', 'does', 'above', 'between', 't', 'be', 'we', 'who', 'were', 'here', 'hers', 'by', 'on', 'about', 'of', 'against', 's', 'or', 'own', 'into', 'yourself', 'down', 'your', 'from', 'her', 'their', 'there', 'been', 'whom', 'too', 'themselves', 'was', 'until', 'more', 'himself', 'that', 'but', 'don', 'with', 'than', 'those', 'he', 'me', 'myself', 'these', 'up', 'will', 'below', 'can', 'theirs', 'my', 'and', 'then', 'is', 'am', 'it', 'an', 'as', 'itself', 'at', 'have', 'in', 'any', 'if', 'again', 'no', 'when', 'same', 'how', 'other', 'which', 'you', 'after', 'most', 'such', 'why', 'a', 'off', 'i', 'yours', 'so', 'the', 'having', 'once'"
Summarizing a dictionary of arrays in Python,"sorted(iter(mydict.items()), key=lambda tup: sum(tup[1]), reverse=True)[:3]"
Row-wise indexing in Numpy,"i = np.array([[0], [1]])"
Change matplotlib line style mid-graph,plt.show()
Read into a bytearray at an offset?,bytearray('\x00\x00\x00\x01\x02\x03\x04\x05\x00\x00')
Sorting Python list based on the length of the string,"xs.sort(lambda x, y: cmp(len(x), len(y)))"
Merge two or more lists with given order of merging,"list(ordered_merge([[3, 4], [1, 5], [2, 6]], [1, 2, 0, 0, 1, 2]))"
Get column name where value is something in pandas dataframe,"df_result.apply(get_col_name, axis=1)"
Setting an Item in nested dictionary with __setitem__,"db.__setitem__('a', {'alpha': 'aaa'})"
Adding custom fields to users in django,uinfo.save()
How to store numerical lookup table in Python (with labels),"{'_id': 'run_unique_identifier', 'param1': 'val1', 'param2': 'val2'}"
How to get the values from a NumPy array using multiple indices,"arr[[0, 1, 1], [1, 0, 2]]"
Extract all keys from a list of dictionaries,set([i for s in [list(d.keys()) for d in LoD] for i in s])
Django order by highest number of likes,Article.objects.annotate(like_count=Count('likes')).order_by('-like_count')
Changing image hue with Python PIL,img = Image.open('tweeter.png').convert('RGBA')
Rounding entries in a Pandas DafaFrame,"df.round({'Alabama_exp': 2, 'Credit_exp': 3})"
Double Iteration in List Comprehension,[x for b in a for x in b]
Replacing letters in Python given a specific condition,"['tuberculin 1 Cap(s)', 'tylenol 1 Cap(s)', 'tramadol 2 Cap(s)']"
How to capture the entire string while using 'lookaround' with chars in regex?,"re.findall('\\b(?:b+a)+b+\\b', mystring)"
Parse 4th capital letter of line in Python?,"re.match('(?:.*?[A-Z]){3}.*?([A-Z].*)', s).group(1)"
How do I calculate the md5 checksum of a file in Python?,hashlib.md5('filename.exe').hexdigest()
How to split sub-lists into sub-lists k times? (Python),"split_list([1, 2, 3, 4, 5, 6, 7, 8], 2)"
How to compare two JSON objects with the same elements in a different order equal?,sorted(a.items()) == sorted(b.items())
Limit the number of sentences in a string,"re.match('(.*?[.?!](?:\\s+.*?[.?!]){0,1})', phrase).group(1)"