text stringlengths 185 26.5k |
|---|
<s>[INST] Python, Matplotlib, subplot: How to set the axis range? How can I set the y axis range of the second subplot to e.g. [0,1000] ?
The FFT plot of my data (a column in a text file) results in a (inf.?) spike so that the actual data is not visible.
pylab.ylim([0,1000])
has no effect, unfortunately. This is the w... |
<s>[INST] What can you use Python generator functions for? I'm starting to learn Python and I've come across generator functions, those that have a yield statement in them. I want to know what types of problems that these functions are really good at solving.
[/INST] Generators give you lazy evaluation. You use them ... |
<s>[INST] ImportError: Cannot import name X I have four different files named: main, vector, entity, and physics. I will not post all the code, mostly just the imports, because I think that's where the error is. But if you want, I can post more.
Main:
import time
from entity import Ent
from vector import Vect
#the rest... |
<s>[INST] Python read a single character from the user Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like getch()). I know there's a function in Windows for it, but I'd like something that is cross-platform.
[/INST] Here... |
<s>[INST] How do I create a slug in Django? I am trying to create a SlugField in Django.
I created this simple model:
from django.db import models
class Test(models.Model):
q = models.CharField(max_length=30)
s = models.SlugField()
I then do this:
>>> from mysite.books.models import Test
>>> t=Test(q="aa a a ... |
<s>[INST] Why aren't python nested functions called closures? I have seen and used nested functions in Python, and they match the definition of a closure. So why are they called nested functions instead of closures?
Are nested functions not closures because they are not used by the external world?
UPDATE: I was readin... |
<s>[INST] Lazy Method for Reading Big File in Python? I have a very big file 4GB and when I try to read it my computer hangs.
So I want to read it piece by piece and after processing each piece store the processed piece into another file and read next piece.
Is there any method to yield these pieces ?
I would love to h... |
<s>[INST] check if all elements in a list are identical I need the following function:
Input: a list
Output:
True if all elements in the input list evaluate as equal to each other using the standard equality operator;
False otherwise.
Performance: of course, I prefer not to incur any unnecessary overhead.
I feel it... |
<s>[INST] Get MD5 hash of big files in Python I have used hashlib (which replaces md5 in Python 2.6/3.0) and it worked fine if I opened a file and put its content in hashlib.md5() function.
The problem is with very big files that their sizes could exceed RAM size.
How to get the MD5 hash of a file without loading the w... |
<s>[INST] How to exit from Python without traceback? I would like to know how to I exit from Python without having an traceback dump on the output.
I still want want to be able to return an error code but I do not want to display the traceback log.
I want to be able to exit using exit(number) without trace but in case... |
<s>[INST] How do I execute a string containing Python code in Python? How do I execute a string containing Python code in Python?
[/INST] For statements, use exec(string) (Python 2/3) or exec string (Python 2):
>>> mycode = 'print "hello world"'
>>> exec(mycode)
Hello world
When you need the value of an expression, u... |
<s>[INST] How to comment out a block of Python code in Vim I was wondering if there was any key mapping in Vim to allow me to indent certain lines of code (whether those lines have been selected in visual mode, or n lines above/below current cursor position).
So basically something that converts the following
def my_f... |
<s>[INST] Store output of subprocess.Popen call in a string I'm trying to make a system call in Python and store the output to a string that I can manipulate in the Python program.
#!/usr/bin/python
import subprocess
p2 = subprocess.Popen("ntpq -p")
I've tried a few things including some of the suggestions here:
Retri... |
<s>[INST] Getting a map() to return a list in Python 3.x I'm trying to map a list into hex, and then use the list elsewhere. In python 2.6, this was easy:
A: Python 2.6:
>>> map(chr, [66, 53, 0, 94])
['B', '5', '\x00', '^']
However, on Python 3.1, the above returns a map object.
B: Python 3.1:
>>> map(chr, [66, 53, 0,... |
<s>[INST] Pretty-printing of numpy.array I'm curious, whether there is any way to print formatted numpy.arrays, e.g., in the way similar to this:
x = 1.23456
print '%.3f' % x
If I want to print the numpy.array of floats, it prints several decimals, often in 'scientific' format, which is rather hard to read even for lo... |
<s>[INST] Convert list of dictionaries to Dataframe I have a list of dictionaries like this:
[{'points': 50, 'time': '5:00', 'year': 2010},
{'points': 25, 'time': '6:00', 'month': "february"},
{'points':90, 'time': '9:00', 'month': 'january'},
{'points_h1':20, 'month': 'june'}]
and I want to turn this into a pandas... |
<s>[INST] Having Django serve downloadable files I want users on the site to be able to download files whose paths are obscured so they cannot be directly downloaded.
For instance, I'd like the URL to be something like this, "http://example.com/download/?f=somefile.txt
And on the server, I know that all downloadable fi... |
<s>[INST] Compiled vs. Interpreted Languages I'm trying to get a better understanding of the difference. I've found a lot of explanations online, but they tend towards the abstract differences rather than the practical implications.
Most of my programming experiences has been with CPython (dynamic, interpreted), and Ja... |
<s>[INST] Print a list in reverse order with range()? How can you produce the following list with range() in Python?
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[/INST] Use the 'range' built-in function. The signature is range(start, stop, step). This produces a sequence that yields numbers, starting with start, and ending if st... |
<s>[INST] Numpy array dimensions I'm currently trying to learn Numpy and Python. Given the following array:
import numpy as N
a = N.array([[1,2],[1,2]])
Is there a function that returns the dimensions of a (e.g.a is a 2 by 2 array)?
size() returns 4 and that doesn't help very much.
[/INST] It is .shape:
ndarray.sha... |
<s>[INST] How to retrieve an element from a set without removing it? Suppose the following:
>>>s = set([1, 2, 3])
How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another ... |
<s>[INST] What is an alternative to execfile in Python 3.0? It seems they canceled in Python 3.0 all the easy way to quickly load a script file - both execfile() and reload().
Is there an obvious alternative I'm missing?
[/INST] You are just supposed to read the file and exec the code yourself. 2to3 current replaces
... |
<s>[INST] How do I integrate Ajax with Django applications? I am new to Django and pretty new to Ajax. I am working on a project where I need to integrate the two. I believe that I understand the principles behind them both, but have not found a good explanation of the two together.
Could someone give me a quick expla... |
<s>[INST] Generating a PNG with matplotlib when DISPLAY is undefined I am trying to use networkx with Python. When I run this program it get this error. Is there anything missing?
#!/usr/bin/env python
import networkx as nx
import matplotlib
import matplotlib.pyplot
import matplotlib.pyplot as plt
G=nx.Graph()
G.add_... |
<s>[INST] parsing boolean values with argparse I would like to use argparse to parse boolean command-line arguments written as "--foo True" or "--foo False". For example:
my_program --my_boolean_flag False
However, the following test code does not do what I would like:
import argparse
parser = argparse.ArgumentParser(... |
<s>[INST] How to percent-encode URL parameters in Python? If I do
url = "http://example.com?p=" + urllib.quote(query)
It doesn't encode / to %2F (breaks OAuth normalization)
It doesn't handle Unicode (it throws an exception)
Is there a better library?
[/INST] From the docs:
urllib.quote(string[, safe])
Replace s... |
<s>[INST] How to add to the pythonpath in windows 7? I have a directory which hosts all of my Django apps (C:\My_Projects). I want to add this directory to my pythonpath so I can call the apps directly.
I have tried adding C:\My_Projects\; to my Path variable from the Windows GUI (My Computer > Properties > Advanced Sy... |
<s>[INST] Python argparse: How to insert newline in the help text? I'm using argparse in Python 2.7 for parsing input options. One of my options is a multiple choice. I want to make a list in its help text, e.g.
from argparse import ArgumentParser
parser = ArgumentParser(description='test')
parser.add_argument('-g', ... |
<s>[INST] What is the ellipsis [...] in a Python list? I was playing around in python. I used the following code in IDLE
p = [1, 2]
p[1:1] = [p]
print p
The output was
[1, [...], 2]
What is this [â¦]? Interestingly I could now use this as a list of list of list upto infinity i.e.
p[1][1][1]....
I could write the ... |
<s>[INST] Creating a new dict in Python I want to build a dictionary in Python. However, all the examples that I see are instantiating a dictionary from a list, etc . ..
How do I create a new empty dictionary in Python?
[/INST] Call dict with no parameters
new_dict = dict()
or simply write
new_dict = {}
</s> |
<s>[INST] How do I filter ForeignKey choices in a Django ModelForm? Say I have the following in my models.py:
class Company(models.Model):
name = ...
class Rate(models.Model):
company = models.ForeignKey(Company)
name = ...
class Client(models.Model):
name = ...
company = models.ForeignKey(Company)
... |
<s>[INST] How do I remove/delete a virtualenv? I created an environment with the following command: virtualenv venv --distribute
I cannot remove it with the following command: rmvirtualenv venv
I do an lson my current directory and I still see venv
The only way I can remove it seems to be: sudo rm -rf venv
Note that th... |
<s>[INST] How to get a complete list of object's methods and attributes? dir(re.compile(pattern))
does not return pattern as one of the lists's elements. Namely it returns:
['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn']
According to the manual, it is suppose... |
<s>[INST] What is __future__ in Python used for and how/when to use it, and how it works People including me know there is something in Python called __future__ and it appears in quite a few modules I read. And the dull people like me don't know why it's there, and how/when to use it , even after reading the Python's _... |
<s>[INST] Which version of Python do I have installed? I have to run a Python script on a Windows server. How can I know which version of Python I have, and does it even really matter? I was thinking of updating to latest version of Python.
[/INST] python -V
http://docs.python.org/using/cmdline.html#generic-options
-... |
<s>[INST] How do I remove a substring from the end of a string in Python? I have the following code:
url = 'abcdc.com'
print(url.strip('.com'))
I expected: abcdc
I got: abcd
Now I do
url.rsplit('.com', 1)
Is there a better way?
[/INST] You could do this:
url = 'abcdc.com'
if url.endswith('.com'):
url = url[:-4]... |
<s>[INST] Printing Python version in output How can I print version number for the current Python installation in the output?
[/INST] Try
import sys
print(sys.version)
This prints the full version information string. If you only want the python version number, then Bastien Léonard's solution is the best. You might ... |
<s>[INST] How to get console window width in python Is there a way in python to programmatically determine the width of the console? I mean the number of characters that fits in one line without wrapping, not the pixel width of the window.
Edit
Looking for a solution that works on Linux
[/INST] import os
rows, columns... |
<s>[INST] Python: defaultdict of defaultdict? Is there a way to have a defaultdict(defaultdict(int)) in order to make the following code work?
for x in stuff:
d[x.a][x.b] += x.c_int
d needs to be built ad-hoc, depending on x.a and x.b elements.
I could use:
for x in stuff:
d[x.a,x.b] += x.c_int
but then I wou... |
<s>[INST] How can the euclidean distance be calculated with numpy? I have two points in 3D:
(xa, ya, za)
(xb, yb, zb)
And I want to calculate the distance:
dist = sqrt((xa-xb)^2 + (ya-yb)^2 + (za-zb)^2)
What's the best way to do this with Numpy, or with Python in general? I have:
a = numpy.array((xa ,ya, za))
b = nu... |
<s>[INST] Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields? I have a Person model that has a foreign key relationship to Book. Book has a number of fields, but I'm most concerned about "author" (a standard CharField).
With that being said, in my PersonAdmin model, I'd like to display "... |
<s>[INST] How to get current CPU and RAM usage in Python? What's your preferred way of getting current system status (current CPU, RAM, free disk space, etc.) in Python? Bonus points for *nix and Windows platforms.
There seems to be a few possible ways of extracting that from my search:
Using a library such as PSI (th... |
<s>[INST] DatabaseError: current transaction is aborted, commands ignored until end of transaction block I got a lot of errors with the message :
"DatabaseError: current transaction is aborted, commands ignored until end of transaction block"
after changed from python-psycopg to python-psycopg2 as Django project's dat... |
<s>[INST] Why use Python's os module methods instead of executing shell commands directly? I am trying to understand what is the motivation behind using Python's library functions for executing OS-specific tasks such as creating files/directories, changing file attributes, etc. instead of just executing those commands ... |
<s>[INST] How to write inline if statement for print? I need to print some stuff only when a boolean variable is set to True. So, after looking at this, I tried with a simple example:
>>> a = 100
>>> b = True
>>> print a if b
File "<stdin>", line 1
print a if b
^
SyntaxError: invalid syntax
Same t... |
<s>[INST] How to uninstall Python 2.7 on a Mac OS X 10.6.4? I want to completely remove Python 2.7 from my Mac OS X 10.6.4. I managed to remove the entry from the PATH variable by reverting my .bash_profile. But I also want to remove all directories, files, symlinks, and entries that got installed by the Python 2.7 ins... |
<s>[INST] Split by comma and strip whitespace in Python I have some python code that splits on comma, but doesn't strip the whitespace:
>>> string = "blah, lots , of , spaces, here "
>>> mylist = string.split(',')
>>> print mylist
['blah', ' lots ', ' of ', ' spaces', ' here ']
I would rather end up with whitesp... |
<s>[INST] What exactly are Python's iterator, iterable, and iteration protocols? What are the most basic definitions of "iterable", "iterator" and "iteration" in Python?
I've read multiple definitions but their exact meaning still won't sink in.
Can someone please help me with the basic idea?
[/INST] Iteration is a ge... |
<s>[INST] What is the best way to implement nested dictionaries in Python? I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this:
{'new jersey': {'mercer county': {'plumbers': 3,
'programmers': 81},
'middlesex county': {'... |
<s>[INST] pip: dealing with multiple Python versions? Is there any way to make pip play well with multiple versions of Python? For example, I want to use pip to explicitly install things to either my site 2.5 installation or my site 2.6 installation.
For example, with easy_install, I use easy_install-2.{5,6}.
And, yes ... |
<s>[INST] How to install pip with Python 3? I want to install pip. It should support Python 3, but it requires setuptools, which is available only for Python 2.
How can I install pip with Python 3?
[/INST] I was able to install pip for python 3 on Ubuntu just by running sudo apt-get install python3-pip.
</s> |
<s>[INST] Why does the floating-point value of 4*0.1 look nice in Python 3 but 3*0.1 doesn't? I know that most decimals don't have an exact floating point representation (Is floating point math broken?).
But I don't see why 4*0.1 is printed nicely as 0.4, but 3*0.1 isn't, when
both values actually have ugly decimal rep... |
<s>[INST] Sending HTML email using Python How can I send the HTML content in an email using Python? I can send simple text.
[/INST] From Python v2.6.2 documentation - 19.1.11. email: Examples:
Hereâs an example of how to create an HTML message with an alternative plain text version:
#! /usr/bin/python
import smtp... |
<s>[INST] Python __str__ versus __unicode__ Is there a python convention for when you should implement __str__() versus __unicode__(). I've seen classes override __unicode__() more frequently than __str__() but it doesn't appear to be consistent. Are there specific rules when it is better to implement one versus the ... |
<s>[INST] Reimport a module in python while interactive I know it can be done, but I never remember how.
How can you reimport a module in python?
The scenario is as follows: I import a module interactively and tinker with it, but then I face an error. I fix the error in the .py file and then I want to reimport the fix... |
<s>[INST] Django: Why do some model fields clash with each other? I want to create an object that contains 2 links to Users. For example:
class GameClaim(models.Model):
target = models.ForeignKey(User)
claimer = models.ForeignKey(User)
isAccepted = models.BooleanField()
but I am getting the following error... |
<s>[INST] numpy: access an array by column Suppose I have:
test = numpy.array([[1, 2], [3, 4], [5, 6]])
test[i] gets me ith line of the array (eg [1, 2]). How can I access the ith column? (eg [1, 3, 5]). Also, would this be an expensive operation?
[/INST] >>> test[:,0]
array([1, 3, 5])
Similarly,
>>> test[1,:]
arra... |
<s>[INST] how to get row count of pandas dataframe? I'm trying to get the number of rows of dataframe df with Pandas, and here is my code
Method 1:
total_rows = df.count
print total_rows +1
Method 2:
total_rows = df['First_columnn_label'].count
print total_rows +1
both the code snippets give me this error:
TypeErro... |
<s>[INST] How to check version of python modules? I just installed the python modules: construct and statlib with setuptools like this:
# Install setuptools to be able to download the following
sudo apt-get install python-setuptools
# Install statlib for lightweight statistical tools
sudo easy_install statlib
# Insta... |
<s>[INST] Using Django time/date widgets in custom form How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?
I have looked through the Django forms documentation, and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?
Here is my templat... |
<s>[INST] How do I convert local time to UTC in Python? How do I convert a datetime string in local time to a string in UTC time?
I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.
Clarification: For example, if I have 2008-09-17 14:02:00 in my local timezon... |
<s>[INST] Choosing Java vs Python on Google App Engine Currently Google App Engine supports both Python & Java. Java support is less mature. However, Java seems to have a longer list of libraries and especially support for Java bytecode regardless of the languages used to write that code. Which language will give bette... |
<s>[INST] Using sphinx with Markdown instead of RST I hate RST but love sphinx. Is there a way that sphinx reads markdown instead of reStructuredText?
[/INST] The "proper" way to do that would be to write a docutils parser for markdown. (Plus a Sphinx option to choose the parser.) The beauty of this would be instant... |
<s>[INST] Django datetime issues (default=datetime.now()) I have such db model:
from datetime import datetime
class TermPayment(models.Model):
# cut out some fields, non relevant to the question
date = models.DateTimeField(default=datetime.now(), blank=True)
And when new instance is added:
tp = TermPaymen... |
<s>[INST] Multiple variables in Python 'with' statement Is it possible to declare more than one variable using a with statement in Python?
Something like:
from __future__ import with_statement
with open("out.txt","wt"), open("in.txt") as file_out, file_in:
for line in file_in:
file_out.write(line)
... or ... |
<s>[INST] Python date string to date object How do I convert a string to a date object in python?
The string would be: "24052010" (corresponding to the format: "%d%m%Y")
I don't want a datetime.datetime object, but rather a datetime.date
[/INST] You can use strptime in the datetime package of Python:
>>> datetime.dat... |
<s>[INST] How are Python's Built In Dictionaries Implemented Does anyone know how the built in dictionary type for python is implemented? My understanding is that it is some sort of hash table, but I haven't been able to find any sort of definitive answer.
[/INST] Here is everything about Python dicts that I was able... |
<s>[INST] How to iterate over rows in a DataFrame? I have a DataFrames from pandas:
import pandas as pd
inp = [{'c1':10, 'c2':100}, {'c1':11,'c2':110}, {'c1':12,'c2':120}]
df = pd.DataFrame(inp)
print df
Output:
c1 c2
0 10 100
1 11 110
2 12 120
Now I want to iterate over the rows of the above frame. For ev... |
<s>[INST] Split python string every nth character?
Possible Duplicate:
What is the most “pythonic” way to iterate over a list in chunks?
Is it possible to split a python string every nth character?
For example, suppose I have a string containing the following:
'1234567890'
How can I get it to look like this:
['12',... |
<s>[INST] Read password from stdin Scenario: An interactive CLI Python program, that is in need for a password. That means also, there's no GUI solution possible.
In bash I could get a password read in without re-prompting it on screen via
read -s
Is there something similar for Python? I.e.,
password = raw_input('Pass... |
<s>[INST] How to filter the DataFrame rows of pandas by "within"/"in"? I have a Python pandas DataFrame rpt:
rpt
<class 'pandas.core.frame.DataFrame'>
MultiIndex: 47518 entries, ('000002', '20120331') to ('603366', '20091231')
Data columns:
STK_ID 47518 non-null values
STK_Name 4751... |
<s>[INST] How to serve static files in Flask So this is embarrassing. I've got an application that I threw together in Flask and for now it is just serving up a single static HTML page with some links to CSS and JS. And I can't find where in the documentation Flask describes returning static files. Yes, I could use ren... |
<s>[INST] Is a Python list guaranteed to have its elements stay in the order they are inserted in? If I have the following Python code
>>> x = []
>>> x = x + [1]
>>> x = x + [2]
>>> x = x + [3]
>>> x
[1, 2, 3]
Will x be guaranteed to always be [1,2,3], or are other orderings of the interim elements possible?
[/INST] ... |
<s>[INST] How does collections.defaultdict work? I've read the examples in python docs, but still can't figure out what this method means. Can somebody help? Here are two examples from the python docs
>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
... d[k] += 1
...
>>> d.items()
[('i', 4), ('p', 2),... |
<s>[INST] Python: Extract numbers from a string I would extract all the numbers contained in a string. Which is the better suited for the purpose, regular expressions or the isdigit() method?
Example:
line = "hello 12 hi 89"
Result:
[12, 89]
[/INST] I'd use a regexp :
>>> import re
>>> re.findall(r'\d+', 'hello 42 I... |
<s>[INST] Print the full numpy array When I print a numpy array, I get a truncated representation, but I want the full array.
Is there any way to do this?
Examples:
>>> numpy.arange(10000)
array([ 0, 1, 2, ..., 9997, 9998, 9999])
>>> numpy.arange(10000).reshape(250,40)
array([[ 0, 1, 2, ..., 37, 38... |
<s>[INST] Why is IoC / DI not common in Python? In Java IoC / DI is a very common practice which is extensively used in web applications, nearly all available frameworks and Java EE. On the other hand, there are also lots of big Python web applications, but beside of Zope (which I've heard should be really horrible to ... |
<s>[INST] Best way to log a Python exception I'm printing my exceptions to a log file currently with:
try:
# coode in here
except Exception, e:
logging.error(e)
Could I be printing more information about the exception and the code that generated it than just the exception string? Things like line numbers or st... |
<s>[INST] Why wasn't PyPy included in standard Python? I was looking at PyPy and I was just wondering why it hasn't been adopted into the mainline Python distributions. Wouldn't things like JIT compilation and lower memory footprint greatly improve the speeds of all Python code?
In short, what are the main drawbacks of... |
<s>[INST] Adding 5 days to a date in Python I have a date "10/10/11(m-d-y)" and I want to add 5 days to it using a Python script. Please consider a general solution that works on the month ends also.
I am using following code:
import re
from datetime import datetime
StartDate = "10/10/11"
Date = datetime.strptime(Sta... |
<s>[INST] How to write a Python module? I've been making Python scripts for simple tasks at work and never really bothered packaging them for others to use. Now I have been assigned to make a Python wrapper for a REST API. I have absolutely no idea on how to start and I need help.
What I have:
(Just want to be specific... |
<s>[INST] Python list of dictionaries search Assume I have this:
[
{"name": "Tom", "age": 10},
{"name": "Mark", "age": 5},
{"name": "Pam", "age": 7}
]
and by searching "Pam" as name, I want to retrieve the related dictionary: {name: "Pam", age: 7}
How to achieve this ?
[/INST] You can use a generator expression:
>>> ... |
<s>[INST] Python: create object and add attributes to it I want to create a dynamic object (inside another object) in Python and then add attributes to it.
I tried:
obj = someobject
obj.a = object()
setattr(obj.a, 'somefield', 'somevalue')
but this didn't work.
Any ideas?
edit:
I am setting the attributes from a for l... |
<s>[INST] String Interpolation in Python Is there a Python equivalent to Ruby's string interpolation?
Ruby example:
name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea? \n#{name}."
Whilst I could succeed using string concatenation in Python, it's seemingly verbose to me coming from Ruby.
[/INS... |
<s>[INST] What is the difference between pip and conda? I know pip is a package manager for python packages. However, I saw the installation on iPython's website use conda to install iPython.
Can I use pip to install iPython? Why should I use conda as another python package manager when I already have pip?
What is the ... |
<s>[INST] Find full path of the Python interpreter? How do I find the full path of the currently running Python interpreter from within the currently executing Python script?
[/INST] sys.executable contains full path of the currently running Python interpreter.
import sys
print(sys.executable)
which is now documente... |
<s>[INST] In Python, what is the difference between '/' and '//' when used for division? Is there a benefit to using one over the other? They both seem to return the same results.
>>> 6/3
2
>>> 6//3
2
[/INST] In Python 3.0, 5 / 2 will return 2.5 and 5 // 2 will return 2. The former is floating point division, and th... |
<s>[INST] Redirect stdout to a file in Python? How do I redirect stdout to an arbitrary file in Python?
When a long-running Python script (e.g, web application) is started from within the ssh session and backgounded, and the ssh session is closed, the application will raise IOError and fail the moment it tries to write... |
<s>[INST] Find and list duplicates in Python list How can I find the duplicates in a Python list and create another list of the duplicates? The list is just integers.
[/INST] To remove duplicates use set(a), to print duplicates - something like
a = [1,2,3,2,1,5,6,5,5,5]
import collections
print [item for item, count... |
<s>[INST] What's the difference between filter and filter_by in SQLAlchemy? Could anyone explain the difference between filter and filter_by functions in SQLAlchemy? I am confused and can't really see the difference. Which one should I be using?
[/INST] filter_by is used for simple queries on the column names like
db.... |
<s>[INST] How do I calculate the date six months from the current date using the datetime Python module? I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?
The reason I want to generate a date 6 months from the curre... |
<s>[INST] ImportError: No module named requests Whenever I run this code, I consistently get an error saying No module Named requests:
import requests
The error I get:
File "ex2.py", line 1, in <module>
import requests
ImportError: No module named requests
[/INST] Requests is not a built in module, so you will ... |
<s>[INST] How do I clone a Django model instance object and save it to the database? Foo.objects.get(pk="foo")
<Foo: test>
In the database, I want to add another object which is a copy of the object above.
Suppose my table has one row. I want to insert the first row object into another row with a different primary key... |
<s>[INST] In Python, when to use a Dictionary, List or Set? When should I use a dictionary, list or set?
Are there scenarios that are more suited for each data type?
[/INST] A list keeps order, dict and set don't: when you care about order, therefore, you must use list (if your choice of containers is limited to these... |
<s>[INST] Making Python loggers output all messages to stdout in addition to log Is there a way to make Python logging using the logging module automatically output things to stdout in addition to the log file where they are supposed to go? For example, I'd like all calls to logger.warning, logger.critical, logger.erro... |
<s>[INST] Generating an MD5 checksum of a file Is there any simple way of generating (and checking) MD5 checksums of a list of files in Python? (I have a small program I'm working on, and I'd like to confirm the checksums of the files).
[/INST] There is a way that's pretty memory inefficient.
single file:
print hashli... |
<s>[INST] How to terminate a python subprocess launched with shell=True I'm launching a subprocess with the following command:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
However, when I try to kill using:
p.terminate()
or
p.kill()
The command keeps running in the background, so I was wondering ho... |
<s>[INST] Installing SciPy with pip It is possible to install NumPy with pip using pip install numpy.
Is there a similar possibility with SciPy? (Doing pip install scipy does not work.)
Update
The package SciPy is now available to be installed with pip!
[/INST] Prerequisite:
sudo apt-get install build-essential gfor... |
<s>[INST] How to send an email with Gmail as provider using Python? I am trying to send email (Gmail) using python, but I am getting following error.
Traceback (most recent call last):
File "emailSend.py", line 14, in <module>
server.login(username,password)
File "/usr/lib/python2.5/smtplib.py", line 554, in logi... |
<s>[INST] Stripping everything but alphanumeric chars from a string in Python What is the best way to strip all non alphanumeric characters from a string, using Python?
The solutions presented in the PHP variant of this question will probably work with some minor adjustments, but don't seem very 'pythonic' to me.
For t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.