text
stringlengths
4
1.08k
Python: How to make a list of n numbers and randomly select any number?,mylist = list(range(10))
"Matplotlib - labelling points (x,y) on a line with a value z",plt.show()
Django: Grab a set of objects from ID list (and sort by timestamp),objects = Model.objects.filter(id__in=object_ids).order_by('-timestamp')
How to get the size of a string in Python?,print(len('abc'))
How to get the size of a string in Python?,print(len('\xd0\xb9\xd1\x86\xd1\x8b'))
Map two lists into a dictionary in Python,"list(zip(keys, values))"
Receiving Broadcast Packets in Python,"s.bind(('', 12345))"
How to find most common elements of a list?,"['you', 'i', 'a']"
Imshow subplots with the same colorbar,plt.colorbar()
Regex for removing data in parenthesis,"print(re.sub(' \\(\\w+\\)', '', item))"
Python - verifying if one list is a subset of the other,"set([1, 2, 2]).issubset([1, 2])"
How to display the value of the bar on each bar with pyplot.barh()?,plt.show()
Best way to split every nth string element and merge into array?,list(itertools.chain(*[item.split() for item in lst]))
Encoding a string to ascii,"s = s.decode('some_encoding').encode('ascii', 'replace')"
How to invert colors of an image in pygame?,pygame.display.flip()
removing pairs of elements from numpy arrays that are NaN (or another value) in Python,np.isnan(a).any(1)
Setting default value for integer field in django models,models.PositiveSmallIntegerField(default=0)
Cannot import SQLite with Python 2.6,sys.path.append('/your/dir/here')
How do I get Python's ElementTree to pretty print to an XML file?,f.write(xmlstr.encode('utf-8'))
random byte string in python,"buf = '\x00' + ''.join(chr(random.randint(0, 255)) for _ in range(4)) + '\x00'"
Python: how to find common values in three lists,"set(a).intersection(b, c)"
hex string to character in python,binascii.unhexlify('437c2123')
Make a dictionary in Python from input values,"{'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}"
pandas: best way to select all columns starting with X,df.columns.map(lambda x: x.startswith('foo'))
surface plots in matplotlib,plt.show()
How to convert an hexadecimale line in a text file to an array (Python)?,"al_arrays = [[l[i:i + 2] for i in range(0, len(l.strip()), 2)] for l in In_f]"
Sort Python dict by datetime value,"sorted(dct, key=dct.get)"
Using headers with the Python requests library's get method,"r = requests.get('http://www.example.com/', headers={'content-type': 'text'})"
Get a unique computer ID in Python on windows and linux,subprocess.Popen('dmidecode.exe -s system-uuid'.split())
Return multiple lists from comprehension in python,"x, y = zip(*[(i, -1 * j) for i, j in enumerate(range(10))])"
How do I get the modified date/time of a file in Python?,os.path.getmtime(filepath)
How do you select choices in a form using Python?,form['favorite_cheese'] = ['brie']
Get IP address of url in python?,print(socket.gethostbyname('google.com'))
Getting the row index for a 2D numPy array when multiple column values are known,"np.where(np.any(a == 2, axis=0) & np.any(a == 5, axis=0))"
How do I change the range of the x-axis with datetimes in MatPlotLib?,"ax.set_ylim([0, 5])"
Python version 2.7: XML ElementTree: How to iterate through certain elements of a child element in order to find a match,element.find('visits')
how to print decimal values in python,gpb = float(eval(input()))
In Python how do you split a list into evenly sized chunks starting with the last element from the previous chunk?,splitlists[-1].append(splitlists[0][0])
Extracting stderr from pexpect,child.expect('hi')
How can I parse a website using Selenium and Beautifulsoup in python?,driver.get('http://news.ycombinator.com')
How to plot a 3D patch collection in matplotlib?,plt.show()
Easiest way to remove unicode representations from a string in python 3?,"re.sub('(\\\\u[0-9A-Fa-f]+)', unescapematch, t)"
Wtforms: How to generate blank value using select fields with dynamic choice values,"form.group_id.choices.insert(0, ('', ''))"
Matplotlib bar graph x axis won't plot string values,plt.show()
Can I sort text by its numeric value in Python?,"[('0', 10), ('1', 23), ('2.0', 321), ('2.1', 3231), ('3', 3), ('12.1.1', 2)]"
How to select increasing elements of a list of tuples?,"a = [a[i] for i in range(1, len(a)) if a[i][1] > a[i - 1][1]]"
Insert row into Excel spreadsheet using openpyxl in Python,wb.save(file)
sorting a list of tuples in Python,"sorted([(1, 3), (3, 2), (2, 1)], key=itemgetter(1))"
How to match beginning of string or character in Python,"re.findall('[a]', 'abcd')"
Python split consecutive delimiters,"re.split('a+', 'aaa')"
How to find the indexes of matches in two lists,"[i for i, (a, b) in enumerate(zip(vec1, vec2)) if a == b]"
Repeating elements in list comprehension,[i for i in range(3) for _ in range(2)]
Duplicate items in legend in matplotlib?,"ax.plot(x, y, label='Representatives' if i == 0 else '')"
Regular expression parsing a binary file?,r = re.compile('(This)')
Setting path to firefox binary on windows with selenium webdriver,driver = webdriver.Firefox()
Convert Django Model object to dict with all of the fields intact,list(SomeModel.objects.filter(id=instance.id).values())[0]
Python - concatenate a string to include a single backslash,print('INTERNET\\jDoe')
How to set Python version by default in FreeBSD?,PYTHON_DEFAULT_VERSION = 'python3.2'
How to alphabetically sort array of dictionaries on single key?,"sorted(my_list, key=operator.itemgetter('name', 'age', 'other_thing'))"
How to create an immutable list in Python?,y = list(x)
How to convert triangle matrix to square in NumPy?,"np.where(np.triu(np.ones(A.shape[0], dtype=bool), 1), A.T, A)"
Opening and reading a file with askopenfilename,f.close()
Django filter JSONField list of dicts,Test.objects.filter(actions__contains={'fixed_key_1': 'foo2'})
Access an arbitrary element in a dictionary in Python,list(dict.keys())[0]
Is there a random letter generator with a range?,random.choice(string.ascii_letters[0:4])
How to count the number of occurences of `None` in a list?,len([x for x in lst if x is not None])
Merge Columns within a DataFrame that have the Same Name,"df.groupby(df.columns, axis=1).agg(numpy.max)"
Removing duplicates in each row of a numpy array,numpy.array([v for v in vals if len(set(v)) == len(v)])
No minor grid lines on the x-axis only,"axes.xaxis.grid(False, which='minor')"
Open web in new tab Selenium + Python,"browser.execute_script('window.open(""http://bings.com"",""_blank"");')"
Finding which rows have all elements as zeros in a matrix with numpy,np.where(~a.any(axis=1))
How to assert that a method is decorated with python unittest?,"assert getattr(MyClass.my_method, '__wrapped__').__name__ == 'my_method'"
pandas dataframe select columns in multiindex,"df.xs('A', level='Col', axis=1)"
How can I make multiple empty arrays in python?,listOfLists = [[] for i in range(N)]
numpy IndexError: too many indices for array when indexing matrix with another,"matrix([[1, 2, 3], [7, 8, 9], [10, 11, 12]])"
Assigning a value to Python list doesn't work?,l = [0] * N
How to disable the minor ticks of log-plot in Matplotlib?,plt.show()
Convert a list into a nested dictionary,print(d['a']['b']['c'])
"How to store data frame using PANDAS, Python",df = pd.read_pickle(file_name)
How to convert false to 0 and true to 1 in python,x = int(x == 'true')
Python convert csv to xlsx,workbook.close()
Get 'popular categories' in django,Category.objects.annotate(num_books=Count('book')).order_by('num_books')
How can I make a blank subplot in matplotlib?,plt.show()
How to quit a pygtk application after last window is closed/destroyed,"window.connect('destroy', gtk.main_quit)"
"How to do an inverse `range`, i.e. create a compact range based on a set of numbers?","[1, 1, 2, 2]"
"I need to securely store a username and password in Python, what are my options?","keyring.get_password('system', 'username')"
How to send a session message to an anonymous user in a Django site?,request.session['message'] = 'Some Error Message'
How to replace the nth element of multi dimension lists in Python?,"a = [['0', '0'], ['0', '0'], ['0', '0']]"
How to create an integer array in Python?,"a = array.array('i', (0 for i in range(0, 10)))"
Sort a list based on dictionary values in python?,"sorted(trial_list, key=lambda x: trial_dict[x])"
How can I log outside of main Flask module?,app.run()
How can I set the y axis in radians in a Python plot?,"ax.plot(x, y, 'b.')"
"python: dictionary to string, custom format?",""""""", """""".join('='.join((str(k), str(v))) for k, v in list(mydict.items()))"
How to iterate through sentence of string in Python?,""""""" """""".join(PorterStemmer().stem_word(word) for word in text.split(' '))"
fill missing indices in pandas,x.resample('D').fillna(0)
Return a list of weekdays,print(weekdays('Wednesday'))
"python-social-auth and Django, replace UserSocialAuth with custom model",SOCIAL_AUTH_STORAGE = 'proj.channels.models.CustomSocialStorage'
How to write unicode strings into a file?,f.write(s.encode('UTF-8'))
How to choose bins in matplotlib histogram,"plt.hist(x, bins=list(range(-4, 5)))"
Python remove anything that is not a letter or number,"re.sub('[\\W_]+', '', s, flags=re.UNICODE)"