text
stringlengths
4
1.08k
Why does a Python bytearray work with value >= 256,bytearray('\xff')
How to update a plot with python and Matplotlib,plt.draw()
Finding the index of an item given a list containing it in Python,"['foo', 'bar', 'baz'].index('bar')"
How can I capture the stdout output of a child process?,sys.stdout.flush()
How to find number of days in the current month,"print(calendar.monthrange(now.year, now.month)[1])"
how to send the content in a list from server in twisted python?,client.transport.write(message)
How to write a list to xlsx using openpyxl,cell.value = statN
How do you extract a column from a multi-dimensional array?,return [row[i] for row in matrix]
"From a list of floats, how to keep only mantissa in Python?",[(a - int(a)) for a in l]
Python matplotlib decrease size of colorbar labels,cbar.ax.tick_params(labelsize=10)
Django One-To-Many Models,vulnerability = models.ForeignKey(Vuln)
Create 3D array using Python,[[[(0) for _ in range(n)] for _ in range(n)] for _ in range(n)]
How to make two markers share the same label in the legend using matplotlib?,plt.show()
List of unicode strings,"['aaa', 'bbb', 'ccc']"
Passing meta-characters to Python as arguments from command line,"""""""\\t\\n\\v\\r"""""".decode('string-escape')"
Numpy matrix to array,A = np.squeeze(np.asarray(M))
How to set default text for a Tkinter Entry widget,root.mainloop()
Print a string as hex bytes?,""""""":"""""".join(x.encode('hex') for x in 'Hello World!')"
How to remove NaN from a Pandas Series where the dtype is a list?,pd.Series([np.array(e)[~np.isnan(e)] for e in x.values])
How to input a word in ncurses screen?,curses.endwin()
How to perform OR condition in django queryset?,User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True))
Django: Ordered list of model instances from different models?,MediaItem.objects.all().order_by('upload_date').select_subclasses()
Efficiently applying a function to a grouped pandas DataFrame in parallel,"df.set_index('key', inplace=True)"
resampling non-time-series data,df.groupby('rounded_length').mean().force
sampling random floats on a range in numpy,"np.random.uniform(5, 10, [2, 3])"
Sorting a heterogeneous list of objects in Python,"sorted(itemized_action_list, key=attrgetter('priority'))"
Saving a numpy array with mixed data,"numpy.savetxt('output.dat', my_array.reshape((1, 8)), fmt='%f %i ' * 4)"
Generate a random letter in Python,random.choice(string.letters)
matplotlib savefig image size with bbox_inches='tight',"plt.savefig('/tmp/test.png', dpi=200)"
Map two lists into one single list of dictionaries,"return [dict(zip(keys, values[i:i + n])) for i in range(0, len(values), n)]"
printing bit representation of numbers in python,"""""""{0:16b}"""""".format(4660)"
printing bit representation of numbers in python,"""""""{0:016b}"""""".format(4660)"
What is the proper way to format a multi-line dict in Python?,"nested = {a: [(1, 'a'), (2, 'b')], b: [(3, 'c'), (4, 'd')]}"
Using pytz to convert from a known timezone to local,(local_dt - datetime.datetime.utcfromtimestamp(timestamp)).seconds
Numpy repeat for 2d array,"res = np.zeros((arr.shape[0], m), arr.dtype)"
Faster convolution of probability density functions in Python,"convolve_many([[0.6, 0.3, 0.1], [0.5, 0.4, 0.1], [0.3, 0.7], [1.0]])"
Numpy int array: Find indices of multiple target ints,"np.where(np.in1d(values, searchvals))"
How to write custom python logging handler?,logger.setLevel(logging.DEBUG)
"How to get value on a certain index, in a python list?","dictionary = dict(zip(List[0::2], List[1::2]))"
Is there a way to make multiple horizontal boxplots in matplotlib?,"plt.subplot('{0}{1}{2}'.format(1, totfigs, i + 1))"
Pythonic way of removing reversed duplicates in list,data = {tuple(sorted(item)) for item in lst}
How to pass callable in Django 1.9,"url('^$', 'recipes.views.index'),"
How to append to the end of an empty list?,list1 = [i for i in range(n)]
Filter columns of only zeros from a Pandas data frame,df.apply(lambda x: np.all(x == 0))
pandas scatter plotting datetime,"df.plot(x=x, y=y, style='.')"
UnboundLocalError: local variable 'x' referenced before assignment. Proper use of tsplot in seaborn package for a dataframe?,"sns.tsplot(melted, time=0, unit='variable', value='value')"
Subset of dictionary keys,{v[0]: data[v[0]] for v in list(by_ip.values())}
print a progress-bar processing in Python,sys.stdout.flush()
Django - how to filter using QuerySet to get subset of objects?,Kid.objects.filter(id__in=toy_owners)
Get file creation time with Python on Mac,return os.stat(path).st_birthtime
How to read numbers in text file using python?,data = [[int(v) for v in line.split()] for line in lines]
Split words in a nested list into letters,[list(l[0]) for l in mylist]
creating sets of tuples in python,"mySet = set(itertools.product(list(range(1, 51)), repeat=2))"
Escape double quotes for JSON in Python,json.dumps(s)
Average of tuples,sum(v[0] for v in list(d.values())) / float(len(d))
How do I convert a datetime.date object into datetime.datetime in python?,"datetime.datetime.combine(dateobject, datetime.time.min)"
Removing a list of characters in string,"s.translate(None, ',!.;')"
How to convert a python set to a numpy array?,numpy.array(list(c))
Easiest way to replace a string using a dictionary of replacements?,pattern = re.compile('|'.join(list(d.keys())))
Categorize list in Python,"[ind for ind, sub in enumerate(totalist) if sub[:2] == ['A', 'B']]"
Hashing a python dictionary,hash(frozenset(list(my_dict.items())))
How to use sprite groups in pygame,gems = pygame.sprite.Group()
Rotating a two-dimensional array in Python,original[::-1]
Using chromedriver with selenium/python/ubuntu,driver = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver')
How to create a TRIE in Python,"make_trie('foo', 'bar', 'baz', 'barz')"
Update Tkinter Label from variable,root.mainloop()
Get only certain fields of related object in Django,"Users.objects.filter(id=comment.user_id).values_list('name', 'email')"
sum of products for multiple lists in python,"sum([(x * y) for x, y in zip(*lists)])"
python how to pad numpy array with zeros,result = np.zeros(b.shape)
Getting column values from multi index data frame pandas,"df.loc[df.xs('Panning', axis=1, level=1).eq('Panning').any(1)]"
Add tuple to a list of tuples,"c = [tuple(x + b[i] for i, x in enumerate(y)) for y in a]"
splitting a dictionary in python into keys and values,"keys, values = zip(*list(dictionary.items()))"
how to export a table dataframe in pyspark to csv?,df.write.format('com.databricks.spark.csv').save('mycsv.csv')
Retrieving contents from a directory on a network drive (windows),os.listdir('\\\\server\x0colder\\subfolder\\etc')
How do I connect to a MySQL Database in Python?,db.commit()
Get a sub-set of a Python dictionary,dict([i for i in iter(d.items()) if i[0] in validkeys])
How to get non-blocking/real-time behavior from Python logging module? (output to PyQt QTextBrowser),sys.exit(app.exec_())
Set Colorbar Range in matplotlib,plt.colorbar()
How to print integers as hex strings using json.dumps() in Python,"{'a': '0x1', 'c': '0x3', 'b': 2.0}"
Python int to binary?,bin(10)
Python: load words from file into a set,words = set(open('filename.txt').read().split())
Add a 2d array(field) to a numpy recarray,"rf.append_fields(arr, 'vel', np.arange(3), usemask=False)"
String split formatting in python 3,s.split()
Python Image Library: How to combine 4 images into a 2 x 2 grid?,"blank_image = Image.new('RGB', (800, 600))"
Applying uppercase to a column in pandas dataframe,"df['1/2 ID'] = map(lambda x: x.upper(), df['1/2 ID'])"
How to merge two Python dictionaries in a single expression?,z = dict(list(x.items()) + list(y.items()))
How to create a Python dictionary with double quotes as default quote format?,"{'arun': 'maya', 'bill': 'samantha', 'jack': 'ilena', 'hari': 'aradhana'}"
"Regex, find first - Python","re.findall('<wx\\.(?:.*?)> >', i)"
Python lambda returning None instead of empty string,f = lambda x: '' if x is None else x
How to correctly parse UTF-8 encoded HTML to Unicode strings with BeautifulSoup?,"soup = BeautifulSoup(response.read().decode('utf-8', 'ignore'))"
Replace rarely occurring values in a pandas dataframe,g = df.groupby('column_name')
atomic writing to file with Python,f.write('huzza')
python: how to convert a query string to json string?,"dict((itm.split('=')[0], itm.split('=')[1]) for itm in qstring.split('&'))"
how to make arrow that loops in matplotlib?,plt.show()
Is it possible to draw a plot vertically with python matplotlib?,plt.show()
How do I find out my python path using python?,print(sys.path)
Insert image in openpyxl,wb.save('out.xlsx')
Get column name where value is something in pandas dataframe,"df['column'] = df.apply(lambda x: df.columns[x.argmax()], axis=1)"
How can I print over the current line in a command line application?,sys.stdout.flush()
Remove items from a list while iterating,somelist = [x for x in somelist if not determine(x)]