text stringlengths 4 1.08k |
|---|
Python: Converting string to timestamp with microseconds,"datetime.datetime.strptime(myDate, '%Y-%m-%d %H:%M:%S,%f').timetuple()" |
How to get values from a map and set them into a numpy matrix row?,"l = np.array([list(method().values()) for _ in range(1, 11)])" |
How to plot a rectangle on a datetime axis using matplotlib?,ax.xaxis.set_major_locator(locator) |
split a string at a certain index,"re.split('(?<=\\))\\.', '(1.2).2')" |
is there a Python Equivalent to Memcpy,"socket = socket.socket(('127.0.0.1', port))" |
"Python, trying to get input from subprocess?",sys.stdout.flush() |
combine multiple text files into one text file using python,outfile.write(infile.read()) |
How to set the font size of a Canvas' text item?,"canvas.create_text(x, y, font=('Purisa', rndfont), text=k)" |
Determining application path in a Python EXE generated by pyInstaller,os.path.dirname(sys.argv[0]) |
Create dynamic button in PyQt,button.clicked.connect(self.commander(command)) |
How to reference to the top-level module in Python inside a package?,__init__.py |
How to read user input until EOF?,input_str = sys.stdin.read() |
How can I create a list containing another list's elements in the middle in python?,"list_c = list_c + list_a + ['more'] + list_b + ['var1', 'var2']" |
How to get a list of matchable characters from a regex class,"print(re.findall(pattern, x))" |
"locating, entering a value in a text box using selenium and python",driver.get('http://example.com') |
Trying to use hex() without 0x,"""""""{0:06x}"""""".format(int(line))" |
compare two lists in python and return indices of matched values,"[i for i, item in enumerate(a) if item in b]" |
How to convert nested list of lists into a list of tuples in python 3.3?,[tuple(l) for l in nested_lst] |
Python: remove dictionary from list,thelist[:] = [d for d in thelist if d.get('id') != 2] |
How to indent Python list-comprehensions?,[transform(x) for x in results if condition(x)] |
python getting a list of value from list of dict,"map(lambda d: d['value'], l)" |
Find first item with alphabetical precedence in list with numbers,"min(x for x in lst if isinstance(x, str))" |
How to use Gevents with Falcon?,server.serve_forever() |
"In django, how can I filter or exclude multiple things?","player.filter(name__in=['mike', 'charles'])" |
Resizing window doesn't resize contents in tkinter,"root.grid_rowconfigure(0, weight=1)" |
How do I add space between two variables after a print in Python,"print('%d %.2f' % (count, conv))" |
Python: Find the absolute path of an imported module,os.path.abspath(math.__file__) |
Summing elements in a list,"sum(map(int, l))" |
Convert black and white array into an image in python?,im = Image.fromarray(my_array) |
Convert from ASCII string encoded in Hex to plain ASCII?,"""""""7061756c"""""".decode('hex')" |
List Manipulation in Python with pop(),"interestingelts = (x for x in oldlist if x not in ['a', 'c'])" |
split a list of strings at positions they match a different list of strings,"re.split('|'.join(re.escape(x) for x in list1), s)" |
"Difference between using commas, concatenation, and string formatters in Python",print('here is a number: ' + str(2)) |
String formatting options: pros and cons,"""""""My name is {surname}, {name} {surname}. I am {age}."""""".format(**locals())" |
pandas - DataFrame expansion with outer join,"df.columns = ['user', 'tweet']" |
Applying borders to a cell in OpenPyxl,wb.save('border_test.xlsx') |
Sorting a list of tuples with multiple conditions,list_.sort(key=lambda x: x[0]) |
Syntax error on print with Python 3,print('Hello World') |
How to get only the last part of a path in Python?,os.path.basename('/folderA/folderB/folderC/folderD') |
Find the selected option using BeautifulSoup,"soup.find_all('option', {'selected': True})" |
How to make it shorter (Pythonic)?,do_something() |
element-wise operations of matrix in python,"[[(i * j) for i, j in zip(*row)] for row in zip(matrix1, matrix2)]" |
Sort by key of dictionary inside a dictionary in Python,"result = sorted(iter(promotion_items.items()), key=lambda pair: list(pair[1].items()))" |
Simple way to toggle fullscreen with F11 in PyGTK,"window.connect('key-press-event', fullscreen_toggler)" |
Removing elements from a list containing specific characters,[x for x in l if not '2' in x] |
Print Javascript Exceptions In A QWebView To The Console,sys.exit(app.exec_()) |
Converting integer to binary in python,"""""""{0:08b}"""""".format(6)" |
"Creating a new file, filename contains loop variable, python","f = open('file_' + str(i) + '.dat', 'w')" |
How do I get the username in Python?,print(getpass.getuser()) |
Django model field by variable,"getattr(model, fieldtoget)" |
Merging a Python script's subprocess' stdout and stderr while keeping them distinguishable,"tsk = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)" |
How to read and write multiple files?,output.close() |
Sorting the content of a dictionary by the value and by the key,"sorted(list(d.items()), key=operator.itemgetter(1, 0))" |
how to subquery in queryset in django?,people2 = Person.objects.filter(employee__company='Private') |
How to convert this list into a dictionary,"{'pigeon': '1', 'hate': '10', 'hello': '10', 'would': '5', 'adore': '10'}" |
Counting unique index values in Pandas groupby,ex.groupby(level='A').get_group(1) |
Splitting letters from numbers within a string,"re.split('(\\D+)', s)" |
How do I grab the last portion of a log string and interpret it as json?,"""""""a b c d my json expression"""""".split(maxsplit=4)" |
Matching id's in BeautifulSoup,"print(soupHandler.findAll('div', id=lambda x: x and x.startswith('post-')))" |
How can I append this elements to an array in python?,"['1', '2', '3', '4', 'a', 'b', 'c', 'd']" |
How to define free-variable in python?,foo() |
How to I disable and re-enable console logging in Python?,logging.critical('This is a critical error message') |
Splitting integer in Python?,[int(i) for i in str(number)] |
Print latex-formula with python,plt.show() |
"How to ""fake"" a module safely in a Python package",__init__.py |
looping over all member variables of a class in python,"['blah', 'bool143', 'bool2', 'foo', 'foobar2000']" |
How to run an AppleScript from within a Python script?,os.system(cmd) |
How to replace all occurrences of regex as if applying replace repeatedly,"""""""\\1 xby """"""" |
Fastest way to sort each row in a pandas dataframe,"pd.DataFrame(a, df.index, df.columns)" |
How to make this kind of equality array fast (in numpy)?,"(a1[:, (numpy.newaxis)] == a2).all(axis=2).astype(int)" |
Use Python Selenium to get span text,print(element.get_attribute('innerHTML')) |
Showing a gtk.Calendar in a menu?,gtk.main() |
"Formatting ""yesterday's"" date in python",print(yesterday.strftime('%m%d%y')) |
Multiply two pandas series with mismatched indices,s1.reset_index(drop=True) * s2.reset_index(drop=True) |
Extract Data With Backslash and Double Quote - Python CSV Reader,"data = csv.reader(f, delimiter=',', quotechar='""')" |
finding non-numeric rows in dataframe in pandas?,df.applymap(np.isreal) |
Array initialization in Python,[(i * y + x) for i in range(10)] |
Python Pandas - Re-ordering columns in a dataframe based on column name,"df.reindex_axis(sorted(df.columns), axis=1)" |
Organizing list of tuples,l = list(set(l)) |
How to convert integer value to array of four bytes in python,"tuple(struct.pack('!I', number))" |
Spawn subprocess that expects console input without blocking?,"p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)" |
How to write a only integers numpy 2D array on a txt file,"np.savetxt(fname='newPicksData.txt', X=new_picks.astype(int), fmt='%i')" |
Turning off logging in Paramiko,logging.basicConfig(level=logging.WARN) |
How can I color Python logging output?,"logging.Formatter.__init__(self, msg)" |
Extracting all rows from pandas Dataframe that have certain value in a specific column,data['Value'] == 'TRUE' |
How to find all occurrences of a pattern and their indices in Python,"[x.start() for x in re.finditer('foo', 'foo foo foo foo')]" |
Convert backward slash to forward slash in python,"var.replace('\\', '/')" |
How do I find one number in a string in Python?,"number = re.search('\\d+', filename).group()" |
increase the linewidth of the legend lines in matplotlib,plt.show() |
Sum / Average an attribute of a list of objects in Python,sum(c.A for c in c_list) |
How to convert an integer timestamp back to UTC datetime?,datetime.utcfromtimestamp(float(self.timestamp)) |
"In Python, how can I test if I'm in Google App Engine SDK?","return os.environ['SERVER_NAME'] in ('localhost', 'www.lexample.com')" |
How do I format a number with a variable number of digits in Python?,"""""""{num:0{width}}"""""".format(num=123, width=6)" |
"Python regex, remove all punctuation except hyphen for unicode string","re.sub('\\p{P}', lambda m: '-' if m.group(0) == '-' else '', text)" |
How to create a menu and submenus in Python curses?,curses.doupdate() |
Is it possible for BeautifulSoup to work in a case-insensitive manner?,"soup.findAll('meta', attrs={'name': re.compile('^description$', re.I)})" |
Python: How to Resize Raster Image with PyQt,"pixmap4 = pixmap.scaled(64, 64, QtCore.Qt.KeepAspectRatio)" |
Bulk zeroing of elements in a scipy.sparse_matrix,A = A - A.multiply(B) |
How to check whether screen is off in Mac/Python?,main() |
How to make a class JSON serializable,"{'age': 35, 'dog': {'name': 'Apollo'}, 'name': 'Onur'}" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.